首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Gets(string#)函数跳过第一个gets请求

Gets(string#)函数跳过第一个gets请求
EN

Stack Overflow用户
提问于 2011-08-29 22:17:09
回答 2查看 2.3K关注 0票数 1

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

代码语言:javascript
复制
 #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()”。有人能告诉我这是为什么吗?

EN

回答 2

Stack Overflow用户

发布于 2011-08-29 22:19:48

很可能在wgame之前,您正在执行一些在stdio缓冲区中留下\nscanf

下面是你应该做的几件事:

不要混用gets

  • Don't和
  • scanf使用gets。使用fgets
  • Don't听取人们对fflush(stdin)**. 的建议错了**。

如果非常小心和适度,你可以使用:

代码语言:javascript
复制
/* Right before `wgame` begins. */
while((c = getchar()) != '\n' && c != EOF)
    ;

但是,要知道它应该谨慎使用,丢弃用户输入是危险的。

请阅读该主题的C FAQ,以及有关刷新标准输入的explanation

票数 4
EN

Stack Overflow用户

发布于 2012-12-17 07:25:52

代码语言:javascript
复制
#include<stdio.h>
#include<stdlib.h>
#define size 5

void main()
  {
   char *str,*name[size];
   int i,n;
   scanf("%d",&n);
   printf("%d",n);
   fflush(stdin); // using fflush here gets() isn't skipping else i have to use scanf()
   for(i = 0; i < n; i++)
     {
       str = (char*)malloc(20*sizeof(char));
       printf("enter  a name :\n");
       //scanf("%s",str);
       gets(str);
       name[i]=str;
     }
   printf("the entered names  :\n");
   for(i = 0; i < n; i++)
   puts(name[i]);
  }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7231349

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档