c - 如何在 C 中使用 gets() 打印多个字符串(带空格)?

标签 c gets

在我的 C 程序中,我调用了两次 gets() 以获取用户的输入。第一次要求用户输入全名,第二次要求用户输入 friend 的全名。但是,在第二次调用 gets() 时,它不会等待用户的输入,它只是跳过它并完成程序。这是我的完整代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <math.h>

int main()
{
char fullname[30];
char friendsname[30];
char sentence[70]= "";
char gender;

printf("Enter your full name: ");
gets(fullname);

printf("\n");

printf("%s , Please enter your gender(m/f)? : ", fullname);
scanf("%c", &gender );
puts("\n");

if(gender =='m')
{
printf("Mr. %s , please enter your friends name:", fullname);
gets(friendsname);
puts("\n");
}

else if(gender =='f')
{
printf("Mrs. %s , please enter your friends name:", fullname);
gets(friendsname);
puts("\n");
}



strcat(sentence, "Hello Mr./Mrs. ");
strcat(sentence, friendsname );
strcat(sentence, ", " );
strcat(sentence, fullname);
strcat(sentence, " considered you as a friend. ");

puts(sentence);


return 0;


}

这是一个示例输出:


输入你的全名:布拉德皮特

布拉德皮特,请输入您的性别(男/女)? : 米

先生。布拉德皮特,请输入您的好友姓名:

您好先生/女士。 , 布拉德皮特把你当 friend 。

进程返回 0 (0x0) 执行时间:8.110 秒 按任意键继续。


gets(friendsname); 行被完全跳过,程序由于某种原因继续运行。谁能解释为什么会这样?

最佳答案

NEVER NEVER NEVER NEVER 使用 gets。它在您的代码中引入故障点/安全漏洞。它不再是标准库的一部分。请改用 fgets,请注意,如果有空间,它会尝试将尾随换行符存储到目标缓冲区。

gets(friendsname) 被跳过的原因是在 scanf 调用读取性别之后,输入流中有一个尾随换行符; gets 在任何其他输入之前看到该换行符并立即返回。

解决此问题的一种方法是让您的 scanf 调用使用尾随换行符而不将其分配给任何内容:

scanf(" %c%*c", &gender );

第二个转换说明符中的 * 告诉 scanf 读取单个字符并将其丢弃。此外,格式字符串中的前导空白告诉 scanf 跳过任何前导空白并读取第一个非空白字符。

关于c - 如何在 C 中使用 gets() 打印多个字符串(带空格)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32305676/

相关文章:

c - 相同的 C 指针显示不同的值?

c - 将 csv 文件读入结构数组

c++ - gets() 被认为是 C 函数还是 C++ 函数?

c - c中的获取和malloc

c - scanf() 不接受输入

c - 如何在管道上放置指针?

c - C语言中一个地址减去另一个地址

c - C 中的数组修改

c - gets() 函数和输入中的 '\0' 零字节

c - 无法使用 fgets() 函数读取循环结构内的字符串