【发布时间】:2020-07-03 11:21:29
【问题描述】:
我正在编写一个具有 2 个功能的程序。当他打开程序时,要求用户通过输入 1 或 2 作为输入来选择一个。如果用户输入错误,他将被要求再次输入它的选择。
#include <stdio.h>
char c;
int main() {
printf("What do you wish to do ?\nEnter 1 to convert raw PCM to WAV \nEnter 2 to convert WAV to raw PCM \nChoice : ");
c = fgetc(stdin);
while(c != '1' && c != '2') {
printf("You specified an incorrect input\nEnter 1 to convert raw PCM to WAV\nEnter 2 to convert WAV to raw PCM\nChoice : ");
c = fgetc(stdin);
return 0;
}
我通过输入 78 作为输入来测试这种“输入错误”的情况,但这里是控制台输出:
What do you wish to do ?
Enter 1 to convert WAV to raw PCM
Enter 2 to convert raw PCM to WAV
Choice : 78
You specified an incorrect input
Enter 1 to convert raw PCM to WAV
Enter 2 to convert WAV to raw PCM
Choice : You specified an incorrect input
Enter 1 to convert raw PCM to WAV
Enter 2 to convert WAV to raw PCM
Choice : You specified an incorrect input
Enter 1 to convert raw PCM to WAV
Enter 2 to convert WAV to raw PCM
Choice :
在要求进一步输入之前,它会连续三次显示“输入错误”消息。
这种重复的原因可能是什么?
注意:如果我使用 getchar() 而不是 fgetc(stdin),也会发生同样的事情。
【问题讨论】:
-
两个问题:您按下的
Enter键将作为换行符添加到输入缓冲区,您无需处理;第二个是fgetc返回一个int,这对于EOF检查你是否丢失很重要。