开发者

Gets(string#) function skipping first gets request

I'm working on a project for my own personal leisure and learning. Part of it looks like this:

 #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;

 }

My problem is that the output is skipping over the 开发者_开发问答first "gets(string#)" and proceeding to the next "printf()". Can someone tell me why this is?


It's likely that before wgame you are doing some scanf that leaves a \n in the stdio buffer.

Here are a few things you should do:

  • Don't mix scanf and gets
  • Don't use gets. Use fgets
  • Don't listen to people suggesting fflush(stdin). It's wrong.

With great care and moderation, you could use:

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

However, be aware it should be used sparingly, discarding user input is dangerous.

Read this C FAQ on the subject, and an explanation about flushing stdin.


#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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜