【发布时间】:2021-07-03 21:20:27
【问题描述】:
这是我的程序示例:
#include <stdio.h>
void sum();
int main()
{
char choice[4];
do
{
sum();
printf("\nDo You want to restart the program: yes or no:\n");
fgets(choice, 4, stdin); //error point
} while (choice[0] == 'y' || choice[0] == 'Y');
printf("\nThanking You");
return 0;
}
void sum()
{
int a = 3, b = 4;
printf("sum of two number is %d", a + b);
}
在这个程序中,只有在while 的第一次迭代中,它才会要求choice 中的输入,并且在下一次迭代中,程序会通过取choice 中的任何值自动终止。
以下是代码执行后的结果:
sum of two number is 7
Do You want to restart the program: yes or no:
yes
sum of two number is 7
Do You want to restart the program: yes or no:
Thanking You
[Program finished]
我无法理解它需要在choice 中输入,而我没有使用scanf()(它将换行符留在缓冲区中)。可能是它从可能是空格或其他字符的缓冲区中获取输入,但我不知道它来自哪里?
【问题讨论】: