我的程序测试一个数字是否是两个函数的正整数。但是当我输入一个像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: