我经常看到这样的情况,在一系列要求输入的 printf 语句中,某些 语句不接受输入,即
printf_statement1:
printf_statement2: /*Enter input here*/
即在用户为 statement1 输入输入之前,打印 statement2,允许用户输入输入,然后对 statement3 重复相同的操作&语句4。
什么原因导致出现这种情况?
我遇到过这种情况,但现在不再遇到了,在:
printf("\n\n\t\tName: ");
scanf("%s", name); //initially used gets
printf("\n\n\t\tType: ");
scanf("%c", &type);
printf("\n\n\t\tAddress: "); //initially used gets
scanf("%s", address);
printf("\n\n\t\tDate - of - Birth: ");
scanf("%s", dob); //initially used gets
输出:
Name:
Type: I enter something!
Address:
Date - of - Birth: I enter something!
最佳答案
我知道这个问题已经被标记为已回答,但由于 fflush(stdin)
让我感到畏缩,我想发布一个清除 stdin
的替代方法:
void clear_stdin(void)
{
int c;
do {
c = fgetc(stdin);
} while (c != '\n' && c != EOF);
}
这将清除所有char
,直到出现新行或遇到EOF
。 (您可以将 do..while
的主体和条件粘贴到 while
循环的条件中,但我更喜欢这样编写。)
例如,在想要读取单个 char
后调用该函数会很有用,以防止用户输入超过 1 个字符时似乎跳过后续提示。
还可以考虑使用 fgets()
或通过 scanf()
提供宽度说明符以防止溢出。
关于c - 接收输入时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8798063/