我不知道如何检查用户的输入是否按字母顺序排列。我希望程序:
- 读取用户输入
- 检查它是否按字母顺序排列
- 再次输出名称
我试图使用isdigit
和isalpha
但我无法让它工作。
//checking if name is valid and not a number
int nameCheck(char enteredName)
{
//if the name is alphabetic
/* return and output it */
//else
/* let the user enter it again */
}
//user enters the name
int nameEntering()
{
cout << "please enter your Name.n";
char enteredName;
cin >> enteredName;
nameCheck(enteredName);
return 0;
}
int main()
{
char enteredName;
enteredName = nameEntering();
cout << "Have a nice day " << enteredName << "!n";
return 0;
}
这是我的旧解决方案,根本不起作用。我在另一个网站上找到了它并将其用作"模板"。
int nameCheck(char enteredName)
{
int i = 0;
char str[] = {enteredName};
while (str[i])
{
if (isalpha(str[i])) printf("character %c is alphabeticn", str[i]);
else
cout << "Enter your name again without using numbers or other special characters, please!n";
nameEntering();
i++;
}
return enteredName;
}
我找到了解决方案。
//user enters the name
void nameEntering()
{
cout << "please enter your Name.n";
string enteredName;
cin >> enteredName;
//checking if name is valid and not a number
if (find_if(enteredName.begin(), enteredName.end(), isdigit) !=enteredName.end())
{
system("cls");
cout << "please don't enter numbers or other special characters.n";
cout << "n";
nameEntering();
}
//if valid it outputs name
else
{
coutput(enteredName);
}
}