c - Gets(string#) 函数跳过先获取请求

标签 c string gets

我正在为自己的个人休闲和学习做一个项目。它的一部分看起来像这样:

 #include<stdio.h>
 #include<string.h>
 wgame()
 {
 char string3[12], string2[12], string1[12], string4[12], string5[12];
 memset (string1, 0, 11);
 memset (string2, 0, 11);
 memset (string3, 0, 11);
 memset (string4, 0, 11);
 memset (string5, 0, 11);
 printf("reference C correct\n");
 printf("Okay, so you want a game. Here's one for you\n\n\n");
 printf("This is a word game.\n\n   A noun is a person place or thing.\n   A verb is 
 something that you can get up and do.\n   A subject is what the conversation is about.\n");
 printf("Go ahead, type a subject:\n");
 gets(string3);
 printf("That's a good one. Now, type a verb:\n");
 gets(string2);
 printf("How about another:\n");
 gets(string4);
 printf("Really? Okay. Now, type in a noun:\n");
 gets(string1);
 printf("Cool. How about typing another noun:\n");
 gets(string5);
 printf("Allright, here's how your words fit into this game:\n\n\n\n\n");
 printf("When the %s was %s the %s %s all the other %s", string1, 
 string2, string3, string4, string5);
 return 4;

 }

我的问题是输出跳过第一个“gets(string#)”并继续 下一个“printf()”。谁能告诉我这是为什么?

最佳答案

很可能在 wgame 之前,您正在执行一些 scanf,这会在 stdio 缓冲区中留下一个 \n

以下是您应该做的几件事:

  • 不要混用 scanfgets
  • 不要使用gets。使用 fgets
  • 不要听信别人建议 fflush(stdin)。这是错误的

非常谨慎和适度,您可以使用:

/* Right before `wgame` begins. */
while((c = getchar()) != '\n' && c != EOF)
    ;

但是,请注意它应该谨慎使用,丢弃用户输入是危险的。

阅读此 C FAQ关于这个主题,还有一个explanation关于刷新标准输入。

关于c - Gets(string#) 函数跳过先获取请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7231349/

相关文章:

Python:如何让 StringIO.writelines 接受 unicode 字符串?

c - 指向 C 中结构的指针

调车场算法能否解析POSIX正则表达式?

linux - 如何在 linux shell 中的 for ... in ... 语句中使用字符串作为参数

python - 根据 pandas 数据帧中的值更新字符串中的值

c - 调整 gets() 以避免缓冲区溢出

c - 如何检查 C 中的 gets() 函数返回什么值?

c - gets() 在 while 循环中只接受一次输入

c++ - 如何翻译 GTK+ 应用程序?

代码不起作用。但是调试的时候会出现这样的情况