说我有下面的代码段清洁标准输入缓冲区的问题
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
int main() {
char choice;
char name[5] = "";
do {
printf("a = new name or anything else to quit\nChoice: ");
choice = getchar();
//not doing any error handling....assuming you only click 'a'
switch (choice) {
case 'a':
getchar();
printf("Enter a name which is 4 characters or less: ");
fgets(name, 5, stdin);
printf("Name: %s\n", name);
char c;
while ((c = getchar()) != '\n' && c != EOF);
printf("%c", c);
c = '\0';
break;
default:
break;
}
} while (choice == 'a');
printf("Ending.....press enter now");
getchar();
return 0;
}
什么,我试图在这里的测试是清除缓冲区时,我有4个以上的字符输入到。它可以正常工作,只要我有一个4字符或更多的名字,但是当我输入3个字符或更少时,问题就变成了while循环。它期望来自stdin缓冲区的getchar(),但是这是空的。有什么办法解决这个问题?
我真的不明白你问的是什么,但getchar()返回int,而不是char。你似乎正在寻找最多5个字符后看到换行符,这似乎是好的,但我会使用fgetc而不是getchar(),只是因为你使用fgets,并且如果由于某种原因getchar()不使用相同缓冲区作为fgets(),然后所有投注都关闭。另外,我认为fgets不必null来终止字符串,所以你可能想在那里传递4而不是5,然后设置name [4] ='\ 0';之后。这可能会对您有所帮助,或者您可能想要重新提出问题。 – Alex
我输入名称“abc”,例如.....名称[3]中存储的内容将是'\ n'。现在,因为此时缓冲区中没有任何内容,while循环将从空缓冲区中获取getchar(),这意味着我卡在那里。 –