0

I am programming in C. For some reason is just skips over my fgets and runs the code afterwards and I don't know why.

char content[256];
printf("What do you want it to say?\n");
fgets(content, 256, stdin);
Tanner Ellis
  • 39
  • 1
  • 8

3 Answers3

1

Have you tried flushing stdin? You may have a newline char caught in it that is causing your fgets to return instantly.

This question references a good way to flush the stdin

Community
  • 1
  • 1
EEP
  • 715
  • 1
  • 4
  • 17
1

Recall that I/O can be buffered. If there is anything waiting in the input buffer when your function is called, it will be read in. In the event that the first character in the buffer is a '\n', the function will return immediately and appear to gather no input. Ensure that there is nothing in the input buffer before calling fgets().

bta
  • 43,959
  • 6
  • 69
  • 99
  • What you are saying makes sense, but how do I do that? – Tanner Ellis Jul 13 '12 at 19:47
  • As far as clearing out the input buffer goes, there is sample code in [the C FAQs](http://c-faq.com/stdio/stdinflush2.html) that could be useful. When you encounter problems with stray characters in the input buffer, it's usually a hint that there's something wrong in the I/O code that came *before* this. – bta Jul 13 '12 at 19:47
  • I used the example code, and it works. But for some reason, when it appends the string to a file it adds two enters before it. Any ideas as to why? – Tanner Ellis Jul 13 '12 at 20:02
  • Actually, just one enter before and one after – Tanner Ellis Jul 13 '12 at 20:03
  • @TannerEllis- There's no way to tell based only on your description. You'd need to post [enough code to demonstrate the problem](http://sscce.org/). – bta Jul 13 '12 at 20:12
0
char content[256];
printf("What do you want it to say?\n");
while ( getchar() != '\n');
fgets(content, 256, stdin);

OR did you try this...

 char content[256];
 printf("What do you want it to say?\n");
 fgets(content, 256, stdin);
0aslam0
  • 1,797
  • 5
  • 25
  • 42