C Fgets似乎没有被调用

C Fgets似乎没有被调用,c,C,所以我有一段代码,我使用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(que

所以我有一段代码,我使用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;
}

代码还有许多其他潜在问题,但要解决您询问的问题,应该这样做:用以下内容替换
fflush(stdin)

int ch;
do {
    ch = getchar();
} while (ch != '\n' && ch != EOF);
将从stdin读取,直到行结束或文件结束/错误

理想情况下,将该代码包装在函数中并调用该函数

 fflush(stdin);
不起作用。使用

 getchar();

要通过删除剩余的
换行符
字符来清除输入缓冲区

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");
}
#包括
char YesNo(无效)
{
char-answer='';
做{
if(读取(文件号(标准输入),&answer,sizeof answer)!=sizeof answer)
继续;
答案=tolower(答案);
}而((答案!='y')&&(答案!='n');
返回答案;
}
int main()
{
char*temp=NULL,*question=NULL,temp3[50];
尺寸n=0,rval=0;
printf(“你指的是什么动物?”);
rval=获取行(&temp,&n,stdin);
温度[rval-1]='\0';
printf(“您如何询问%s是否与%s不同?”,“测试”,temp);
rval=getline(&Q,&n,stdin);
问题[rval-1]=“0”;
printf(“如果你对这个问题说是,那么是%s吗?[y/n]”,temp);
fflush(stdout);
如果(YesNo()='y')
printf(“是”);
}

注意:不要忘记检查返回值。

也值得注意,如果我在Windows中用DEV C++运行,但在GCC上没有Linux上,这是有效的。未定义的行为:<代码> FFLUHY(STDIN);<代码>发布
PrintCont()
的定义。另外,作为一般提示,不要将
scanf
fgets
混用,这很难做到正确。使用
fgets
获取行,然后使用
sscanf
解析其中的值,如果您需要两者。它最初不在我的代码中,只是在fgets()对我不起作用后,我开始到处刷新stdin以查看是否还有剩余内容in@Veske请查一下这个词的意思。像“我开始到处刷新stdin,看看是否有东西留在里面”这样的语句根本没有意义,因为您无法刷新
stdin
。当然,它是经过编译的,但您无法运行该代码并获得任何合理的结果。这是未定义的行为。此代码被破坏,
getchar()
返回
int
,因为
EOF
不是字符。请修复。@放松啊是的,谢谢!这还表明,使用
getchar()
&co时犯这种特殊的、常见的错误是多么容易。。。