所以我有这个代码,我使用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(),然后转到调用函数YesNo()的if语句,该函数请求输入scanf()。
YesNO功能:
char YesNo(void){
char answer = ' ';
while (answer != 'y' && answer != 'n') {
scanf(" %c",&answer);
fflush(stdin);
}
return answer;
}
答案 0 :(得分:0)
代码还存在许多其他潜在问题,但要解决您所问的问题,应该这样做:用{:1>替换fflush(stdin)
:
int ch;
do {
ch = getchar();
} while (ch != '\n' && ch != EOF);
将从stdin读取,直到行尾或文件结束/错误。
理想情况下,将该代码包装在函数中并调用它。
答案 1 :(得分:0)
fflush(stdin);
不起作用。使用
getchar();
通过删除剩余的newline
字符
答案 2 :(得分:0)
getline和read函数怎么样?
#include <stdio.h>
char YesNo(void)
{
char answer = ' ';
do {
if (read(fileno(stdin), &answer, sizeof answer) != sizeof answer)
continue;
answer = tolower (answer);
} while ((answer != 'y') && (answer != 'n'));
return answer;
}
int main ()
{
char *temp = NULL, *question = NULL, temp3[50];
size_t n = 0, rval = 0;
printf("What animal did you mean? ");
rval = getline(&temp, &n, stdin);
temp[rval-1] = '\0';
printf("How would you ask if %s is different from %s ? ","test", temp);
rval = getline(&question, &n, stdin);
question[rval-1] = '\0';
printf("And if you say yes to that question, is it %s then ?[y/n]", temp);
fflush (stdout);
if (YesNo () == 'y')
printf ("YES");
}
注意:不要忘记检查返回值。