验证用户输入字符串的大小写模式 (isupper/islower)

Validate case pattern (isupper/islower) on user input string

我需要编写一个程序来检查用户提供的名字和姓氏是否输入正确。该程序需要验证只有每个名称部分的第一个字母是大写的。

我设法编写了检查输入的第一个字符的代码。所以我在输入 "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;
}

最简单的方法就是使用 for/while 循环。循环基本上会重复相同的指令 n 步或直到满足特定条件。

所提供的解决方案非常虚拟,如果您想同时读取名字和姓氏,则必须通过“”分隔符吐出字符串。您可以在 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;
}