【发布时间】:2017-03-27 07:30:56
【问题描述】:
我的程序测试一个数字是否是 2 的幂,适用于正整数。但是当我输入像 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 在第二次迭代期间不会等待。我尝试在每次迭代中清除 numbuff。但没有区别。 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'char。 -
@LPs 但是在这种情况下,如果我只想按一个回车键退出程序,则需要两个回车键才能退出程序。
-
没有。您输入 y 并输入。如果没有第二个
getchar,您将使用fgets使用换行符,使用第二个getchar,您会立即使用换行符,而while 将根据用户回答继续/关闭。顺便说一句,您的代码还有许多其他问题,例如:如果用户键入yes而不是y会发生什么?