gpt4 book ai didi

c - 为什么 gets() 可以正常工作,而 fgets() 却不能?

转载 作者:太空狗 更新时间:2023-10-29 16:06:21 26 4
gpt4 key购买 nike

我做了一个程序,找到了gets(),并使用了它,它很棒,但是当我编译程序时它说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() 获得相同的输出?

最佳答案

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上面关于输入行过长的评论。

关于c - 为什么 gets() 可以正常工作,而 fgets() 却不能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32340168/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com