检查用户输入是否为字母

时间:2016-06-01 11:44:28

标签: c++ input char alphabetic

我不知道如何检查用户的输入是否是字母。我想要该程序:

  1. 阅读用户输入
  2. 检查它是否是字母
  3. 再次输出名称
  4. 我尝试使用isdigitisalpha,但我无法让它发挥作用。

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

    这是我的旧解决方案,根本不起作用。我发现在另一个网站上并将其用作&#34;模板&#34;。

    int nameCheck(char enteredName)
    {
        int i = 0;
        char str[] = {enteredName};
        while (str[i])
            {
                if (isalpha(str[i])) printf("character %c is alphabetic\n",     str[i]);
    
                else
                cout << "Enter your name again without using numbers or other     special characters, please!\n";
                nameEntering();
                i++;
            }
        return enteredName;
    }
    

1 个答案:

答案 0 :(得分:0)

我找到了解决方案。

//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);
    }
}