我需要编写一个程序来检查用户提供的名字和姓氏是否输入正确。程序需要验证每个名称部分的第一个字母是否为大写。
我设法编写了检查输入的第一个字符的代码。所以我有一个问题,例如" JOHN"进入。 正确的输入将是例如" John Smith"。
以下是代码:
#include <iostream>
#include <string>
using namespace std;
int main ()
{
std::string str;
cout << "Type First Name: ";
cin >> str;
if(isupper(str[0]))
{
cout << "Correct!" <<endl;
}
else
{
cout << "Incorrect!" <<endl;
}
system("pause");
return 0;
}
答案 0 :(得分:0)
您可以做的最简单的事情是使用for/while循环。循环基本上会在n个步骤中重复相同的指令,或直到某个条件匹配为止。
提供的解决方案非常虚拟,如果你想同时读取名字和姓氏,你必须通过&#34; &#34;分隔符。您可以使用C / C ++中的strtok()或在C ++中使用find来实现此结果。您可以看到有关如何拆分here的一些示例。
您可以轻松修改代码,如下所示:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
std::string str;
std::vector<std::string> data = { "First", "Last" };
int j;
for (int i = 0; i < 2; i++) {
cout << "Type " << data[i] << " Name: ";
cin >> str;
if (isupper(str[0])) {
for (j = 1; j < str.size(); j++) {
if (!islower(str[j]))
{
cout << "InCorrect!" << endl;
break; // Exit the loow
}
}
if(j==str.size())
cout << "Correct!" << endl;
}
else {
cout << "InCorrect!" << endl;
}
}
system("pause");
return 0;
}