【问题标题】:Gets(string#) function skipping first gets requestGets(string#) 函数跳过首先获取请求
【发布时间】:2011-11-06 01:51:28
【问题描述】:

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

 #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() 应该是 int wgame(void)从不使用gets();它不能安全使用,并且正在从语言中删除。使用有意义的变量名。避免使用“幻数”(1112)。缩进你的代码。

标签: c string gets


【解决方案1】:
#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]);
  }

【讨论】:

  • 您可能想解释一下您在这里所做的事情,以供将来面临类似问题的人们使用 :)
【解决方案2】:

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

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

  • 不要混用 scanfgets
  • 不要使用gets。使用fgets
  • 不要听别人建议fflush(stdin)。错了

小心谨慎,您可以使用:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-18
    • 2018-04-14
    • 1970-01-01
    • 2019-03-05
    • 2019-06-22
    • 2020-10-26
    • 1970-01-01
    相关资源
    最近更新 更多