0

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

  1. 读取用户输入
  2. 检查它是否是字母
  3. 再次输出名称

我尝试使用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;
}

这是我的旧解决方案,根本不起作用。我在另一个网站上找到了它并将其用作“模板”。

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

1 回答 1

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);
    }
}
于 2016-06-02T07:37:16.383 回答