简体   繁体   中英

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

I need to write a program that checks if the user-provided first and last names are correctly typed. The program needs to validate that only the first letter of each name part is uppercase.

I managed to write code that checks the first character of the input. So I have a problem when for example "JOHN" is entered. A correct input would be for example "John Smith".

Here's the code:

#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;
}

The simplest thing you can do is to use a for/while loop. A loop will basically repeat the same instruction for a number of n steps or until a certain condition is matched.

The solution provided is pretty dummy, if you want to read the first name and last name at the same time you will have to spit the string via " " delimiter. You can achieve this result using strtok() in C/C++ or with the help of find in C++. You can see some examples of how to split here .

You can easily modify your code to look like this:

#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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM