代码:
#include <stdio.h>
main() {
int nums[100], i;
char answer;
int count = 0;
double avg;
for (i = 0; i < 100; i++) {
printf("Enter number %d: ", i + 1);
scanf("%d", &nums[i]);
printf("Another? ");
scanf("%c", &answer);
count += nums[i];
}
}
运行:
~> a.out
Enter number 1: 1
Another? Enter number 2: 2
Another? Enter number 3: 3
Another? Enter number 4: 4
Another? Enter number 5: 5
Another? Enter number 6: 6
Another? Enter number 7: 7
Another? Enter number 8: 8
Another? Enter number 9:
它应该问我是否要输入另一个数字,但由于某种原因 scanf 不工作。另外,我需要这样做,以便用户可以输入 100 个数字或低于该数字的任何数字,并提示“您要输入另一个数字”的问题。如果答案是否定的,它终止,如果是,它继续。
最佳答案
您的第一个 scanf 在缓冲区中留下一个换行符。这是因为%d
%c
时忽略尾随空格没有。使用这个廉价技巧制作第二个 scanf
吃空白:
scanf(" %c", &answer);
^
这个问题很常见,您可以在 C FAQ 中阅读更多相关信息.
关于c - 为什么这个 C 程序会完全跳过我的输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9855699/