如何检查输入是否为数字

时间:2015-01-06 14:29:27

标签: c

我试图检查输入是否为数字,如果不是,则表示输入错误。

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!");
    }
}

2 个答案:

答案 0 :(得分:4)

检查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).

答案 1 :(得分:2)

scanf_s,与scanf一样,应该返回成功转换和分配的字段数。因此,请查看scanf_s的返回值,而不是调用isdigit。

isdigit检查其参数是否介于“0”和“9”之间,即介于0x30和0x39之间(48-57)。您的整数menyval成功可能在1到4之间,因此isdigit将失败,因为isdigit实际上是用于字符而不是整数。

相关问题