所以我有这段代码,我使用 fgets() 来读取一个大字符串。但我的程序似乎只是跳过了它,根本不使用它。可能是什么原因?
char temp[50], question[50], temp3[50];
printf("What animal did you mean?");
fgets(temp, 50, stdin);
printf("How would you ask if %s is different from %s\n", PrintCont(abi), temp);
fgets(question, 50, stdin);
printf("And if you say yes to that question, is it %s then?[y/n]", temp);
printf("|%s|\n", question);
if(YesNo() != 'y'){
因此,它会打印出所有内容,跳过 fgets(),然后执行 if 语句,该语句调用函数 YesNo() ,该函数要求使用 scanf() 输入。
是/否功能:
char YesNo(void){
char answer = ' ';
while (answer != 'y' && answer != 'n') {
scanf(" %c",&answer);
fflush(stdin);
}
return answer;
}
最佳答案
代码还有许多其他潜在问题,但要解决您提出的问题,应该这样做:将 fflush(stdin)
替换为:
int ch;
do {
ch = getchar();
} while (ch != '\n' && ch != EOF);
将从标准输入读取直到行尾或文件结束/错误。
理想情况下,将该代码包装在一个函数中并调用它。
关于c - fgets好像没有被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22831789/