如何检查输入是否为数字
How to check if input is a number
我正在尝试检查输入是否为数字,如果不是,则说明输入错误。
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",...)
将 return 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).
scanf_s,像scanf应该return成功转换赋值的字段数。所以查看scanf_s的return值,而不是调用isdigit.
isdigit 检查其参数是否在“0”和“9”之间,即在 0x30 和 0x39 (48-57) 之间。您的整数 menyval 成功时可能在 1 到 4 之间,因此 isdigit 将失败,因为 isdigit 实际上是用于字符而不是整数。
我正在尝试检查输入是否为数字,如果不是,则说明输入错误。
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",...)
将 return 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).
scanf_s,像scanf应该return成功转换赋值的字段数。所以查看scanf_s的return值,而不是调用isdigit.
isdigit 检查其参数是否在“0”和“9”之间,即在 0x30 和 0x39 (48-57) 之间。您的整数 menyval 成功时可能在 1 到 4 之间,因此 isdigit 将失败,因为 isdigit 实际上是用于字符而不是整数。