[英]Check if the input is a whole number in C++ in simple way using isdigit
这是我尝试过的
无论输入如何,它总是表现为假
如果可能的话,我怎么能以一种简单的方式正确地做到这一点,为什么它不起作用?
我正在尝试创建一个条件,询问扫描的用户输入是否是数字之一,如果不是,它要求他们只写一个显示的数字并显示选项是什么。
void konc()
{
exit (0);
}
void scan()
{
int ch = 0;
printf("0 - \n");
printf("1 - \n");
printf("2 - \n");
printf("3 - \n");
printf("4 - \n");
printf("5 - \n");
printf("6 - \n");
printf("7 - \n");
scanf("%d", &ch);
while (isdigit(int(ch)) == false || ch < 0 || ch > 7){
printf("Must be one of the numbers\n");
fflush(stdin);
scan();
}
if (ch == 0){
konc();
}
printf("%d", ch);
scan();
}
int main()
{
scan();
return 0;
}
问题在于检查逻辑。
数字0
与字符'0'
不同(映射到值48
)。
将0
更改为'0'
。 (还有7
)
你有几个问题:
int ch = 0; ... scanf("%d", ch);
需要给scanf
一个指向它正在读取的数据的指针,所以这应该是scanf("%d, &ch);
while (isdigit(int(ch)) == false || ch < 0 || ch > 7){
ch
已经是一个 int,所以使用isdigit
没有意义。 已经是一个数字了。 只需检查范围( while (ch < 0 || ch > 7) {
)
fflush(stdin);
在输入 stream 上使用fflush
是未定义的行为。 摆脱这个。
您应该使用循环跳回顶部,而不是递归调用scan
:
int number; while(1) { printf("0 - \n"); printf("1 - \n"); printf("2 - \n"); printf("3 - \n"); printf("4 - \n"); printf("5 - \n"); printf("6 - \n"); printf("7 - \n"); scanf("%d", &number); if(number < 0 || number > 7) { printf("Must be one of the numbers\n"); continue; // Go back to the top of the loop } break; } // Now number is between 0 and 7
你的逻辑是错误的。 做一个循环,直到用户选择正确的数字。
#include <conio.h>
#include <stdio.h>
int main(void)
{
scan();
}
void scan()
{
printf("Choose any of the following numbers:\n");
do
{
printf("0 - \n");
printf("1 - \n");
printf("2 - \n");
printf("3 - \n");
printf("4 - \n");
printf("5 - \n");
printf("6 - \n");
printf("7 - \n");
char ch; // now it is not undefined
scanf("%c",&ch);
fflush(stdin);
if(ch<48||ch>55) //ascii of '0' is 48 and ascii of '7' is 55.
printf("Must be one of the numbers\n");
else
break;
}while(1);
}
我已经测试过了。它肯定会工作。也不需要 isDigit()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.