为什么gets()正常工作,但fgets()不正常?

时间:2015-09-01 20:16:45

标签: c arrays string

我做了一个程序,发现了gets(),并且使用它,它很棒,但是当我编译程序时它说得到危险,所以然后我搜索了另一个,即使gets()函数使它具有正确的输出,对于将来我宁愿使用一个没有危险的替代方案,这是我偶然发现fgets()的时候。我认为代码会编译相同并具有相同的输出,但是我的if语句都没有被输出。

下面是代码:

#include <stdio.h>
#include <string.h>

int main()
{
        char qOne[10];
        char qTwo[10];
        char guess[40] = "My guess is that you are thinking of a\0";

        printf("TWO QUESTIONS\n");
        printf("Think of an object, and i'll try to guess it.\n\n");

        printf("Question 1) Is it an animal, vegetable, or mineral?\n");
        printf("\n> ");
        //gets(qOne);
        fgets(qOne, 10, stdin);

        printf("\nQuestion 2) Is it bigger than a breadbox? (yes/no)\n");
        printf("\n> ");
        //gets(qTwo);
        fgets(qTwo, 10, stdin);

        printf("\n");

        if(strcmp(qOne, "animal") == 0 && strcmp(qTwo, "no") == 0 ||strcmp(qOne, "animal") == 0 && strcmp(qTwo, "No") == 0)

                printf("%s squirrel.\n", guess);

        else if(strcmp(qOne, "animal") == 0 && strcmp(qTwo, "yes") == 0 ||strcmp(qOne, "animal") == 0 && strcmp(qTwo, "Yes") == 0)

                printf("%s moose.\n", guess);

        else if(strcmp(qOne, "vegetable") == 0 && strcmp(qTwo, "no") == 0 ||strcmp(qOne, "vegetable") == 0 && strcmp(qTwo, "No") == 0)

                printf("%s carrot.\n", guess);

        else if(strcmp(qOne, "vegetable") == 0 && strcmp(qTwo, "yes") == 0 ||strcmp(qOne, "vegetable") == 0 && strcmp(qTwo, "Yes") == 0)

                printf("%s watermelon.\n", guess);

        else if(strcmp(qOne, "mineral") == 0 && strcmp(qTwo, "no") == 0 ||strcmp(qOne, "mineral") == 0 && strcmp(qTwo, "No") == 0)

                printf("%s paper clip.\n", guess);

        else if(strcmp(qOne, "mineral") == 0 && strcmp(qTwo, "yes") == 0 ||strcmp(qOne, "mineral") == 0 && strcmp(qTwo, "Yes") == 0)

                printf("%s Camaro.\n", guess);


        printf("\nI would ask you if I'm right, but I don't actually care.\n");

        return 0;
}

此代码的输出是(输入字符串“animal”和“yes”):

TWO QUESTIONS
Think of an object, and i'll try to guess it.

Question 1) Is it an animal, vegetable, or mineral?

> animal

Question 2) Is it bigger than a breadbox? (yes/no)

> yes


I would ask you if I'm right, but I don't actually care.

但是当我只使用gets()而不是fgets()时,我的代码会给出正确的输出,即:

TWO QUESTIONS
Think of an object, and i'll try to guess it.

Question 1) Is it an animal, vegetable, or mineral?

> animal

Question 2) Is it bigger than a breadbox? (yes/no)

> yes

My guess is that you are thinking of a moose.

I would ask you if I'm right, but I don't actually care.

如何使用fgets()获得相同的输出?

1 个答案:

答案 0 :(得分:6)

fgets()会保留结束行'\n',而gets()则不会。然后比较失败。 @user3121023添加代码以消除潜在的终点线。

if (fgets(qTwo, sizeof qTwo, stdin) == NULL) Handle_EOF();
qTwo[strcspn(qTwo, "\n")] = 0;

Removing trailing newline character from fgets() input

[编辑]

请注意@Keith Thompson以上关于过长输入行的评论。