我试图检查输入是否是一个数字,如果不是它将说,输入是错误的。

int menu()
{
    int menyval;
    printf(" 1. Quit\n 2. Add question \n 3. Competitve \n 4. Show all questions\n");
    scanf_s("%d", &menyval);
    if (isdigit(menyval)==0)
    {
        system("cls");
        return menyval;
    }
    else
    {
        printf("That's not a number!");
    }
}

最佳答案

检查scanf_s()的结果

int menu()
{
    int menyval;
    printf(" 1. Quit\n 2. Add question \n 3. Competitive \n 4. Show all questions\n");
    if (1 == scanf_s("%d", &menyval)) {
        system("cls");
        return menyval;
    }
    else {
        printf("That's not a number!");
    }
}

scanf_s("%d",...)将返回0,1(成功扫描字段的计数)或EOF
1: A number was scanned.
0: Nothing saved `&menyval`, input is not a character representation of a number
   User input remains in `stdin`.
EOF:  End-of-file (or input error occurred).

关于c - 如何检查输入是否为数字,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27800781/

10-11 19:45