Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
396 views
in Technique[技术] by (71.8m points)

c - 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
");
 printf("Okay, so you want a game. Here's one for you


");
 printf("This is a word game.

   A noun is a person place or thing.
   A verb is 
 something that you can get up and do.
   A subject is what the conversation is about.
");
 printf("Go ahead, type a subject:
");
 gets(string3);
 printf("That's a good one. Now, type a verb:
");
 gets(string2);
 printf("How about another:
");
 gets(string4);
 printf("Really? Okay. Now, type in a noun:
");
 gets(string1);
 printf("Cool. How about typing another noun:
");
 gets(string5);
 printf("Allright, here's how your words fit into this game:




");
 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It's likely that before wgame you are doing some scanf that leaves a 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()) != '
' && 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...