[英]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. 所以当输入例如“ JOHN”时,我有一个问题。 A correct input would be for example "John Smith". 正确的输入例如是“ 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. 您可以做的最简单的事情是使用for / while循环。 A loop will basically repeat the same instruction for a number of n steps or until a certain condition is matched. 循环基本上将相同的指令重复n步,或者直到满足特定条件为止。
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++. 您可以在C / C ++中使用strtok()或在C ++中使用find来获得此结果。 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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.