我的程序用来测试一个数字是否为正整数的两个作品的能力。但是当我输入一个像5.4这样的实数时,行c=getchar()
不会等待我的输入。如何正确读取整数?
int main() {
int num;
char c = 'y';
printf("\n\n");
do{
printf("**********************************************\n");
printf("Enter a positive integer to test: ");
scanf("%d",&num);
getchar();
if(num<0) {
printf("cannot accept a negative integer.\n");
}
else
is_power_of_two(num);
printf("Do you want to try again?\nEnter 'y' if yes, else press any other key to exit: ");
c = getchar();
printf("**********************************************\n");
}while(c=='y');
return 0;
}
输出:
Enter a positive number to test: 8
Yes it is a power of 2
Do you want to try again?
Enter 'y' if yes, else press any other key to exit: y
**********************************************
**********************************************
Enter a positive number to test: 7.6
No it is not a power of 2
Do you want to try again?
Enter 'y' if yes, else press any other key to exit: **********************************************
我已经使用fgets和的atoi代替像下面的scanf和的getchar()尝试。但是,在第二次迭代期间,fgets不会等待。我尝试在每次迭代中清除麻木。但没有区别。 getchar()是否也会像scanf一样在缓冲区中保留\ n?
这里发生了什么,有没有一种简单的方法或读取整数的正确方法,而不会造成很大的麻烦?
int main() {
char numbuf[10];
int num;
char c = 'y';
printf("\n\n");
do{
printf("**********************************************\n");
printf("Enter a positive number to test: ");
fgets(numbuf, sizeof(numbuf),stdin);
num = atoi(numbuf);
if(num<0) {
printf("cannot accept a negative integer.\n");
}
else
is_power_of_two(num);
printf("Do you want to try again?\nEnter 'y' if yes, else press any other key to exit: ");
c = getchar();
printf("**********************************************\n");
}while(c=='y');
return 0;
}
输出:
**********************************************
Enter a positive number to test: 9
No it is not a power of 2
Do you want to try again?
Enter 'y' if yes, else press any other key to exit: y
**********************************************
**********************************************
Enter a positive number to test: No it is not a power of 2
Do you want to try again?
Enter 'y' if yes, else press any other key to exit:
您是否希望*能够输入浮点数?然后,用于读取*整数的'scanf'格式不起作用。如果通过调试器中的代码,您会看到'getchar'调用放弃换行符会返回''。',而下一个'getchar'将返回第一个小数。如果您不想读取浮点值,那么使用'fgets',然后使用'strtol'尝试将输入转换为整数。 –
'getchar'意味着从输入流中获取下一个字符,而不是必须等待输入。如果流中已经有一个字符,它不会等待。在这种情况下''.' –
在'fgets'解决方案中,在'c = getchar();'之后添加'getchar();'以在新的'fgets'调用之前消耗''\ n''字符。 – LPs