0

I am reading input from the keyboard to store in variables.

char foo[BUFFER_SIZE];
printf("Enter your string");
fgets(foo, BUFFER_SIZE, stdin);
printf("Enter another thingy"); 

However, the program does not wait for user input and directly goes to the second printf(). How can I fix this? I tried using a while loop but then I reach an infinite loop...

brvh
  • 264
  • 3
  • 15
  • 1
    @SergeBallesta It's not a duplicate, the other post has a `scanf()` causing the problem. – Iharob Al Asimi Jun 05 '15 at 12:50
  • 2
    @iharob : I have seen your answer. But when writing on a terminal, stdout is always flushed before any read can occur. IMHO the only possibility is that there is a `\n` left in the input buffer. If OP explains that the cause is different I will revoke my close vote. – Serge Ballesta Jun 05 '15 at 12:57
  • @SergeBallesta good point, I will check that and delete my answer accordingly. – Iharob Al Asimi Jun 05 '15 at 13:02
  • @SergeBallesta you are totally right, This is what the standard says _Furthermore, characters are intended to be transmitted as a block to the host environment when a buffer is filled, when input is requested on an unbuffered stream, or when input is requested on a line buffered stream_ – Iharob Al Asimi Jun 05 '15 at 13:08
  • @iharob : your answer does not deserve to be deleted. It may not directly solve OP's problem, but there are plenty of worse ones around ;-) – Serge Ballesta Jun 05 '15 at 13:10
  • Yes but it's misleading, and as a contributor to the site that I consider myself I delete it because it's wrong. I didn't know that because I never use `printf()` without `'\n'` unless I explicitly want the text to appear side by side. But I just learned something thanks to you. – Iharob Al Asimi Jun 05 '15 at 13:16
  • Are you suggesting to flush stdin? Because I did use a scanf() in a block above, so maybe this is the cause? – brvh Jun 05 '15 at 13:18
  • @brvh Most likely. Do `getchar();` after the scanf to consume the `\n` left in the input stream. – P.P Jun 05 '15 at 13:36
  • @iharob The text you quoted talks about how streams are buffered. I don't see how that supports Serge's claim. – P.P Jun 05 '15 at 13:37
  • It means that at least the first `printf()` prints something before `fgets()`, my answer assumes that it's after. Most likely the `fgets()` reads something that is waiting on `stdin` to be read, like `'\n'` left from a previous `scanf()`, so this question shall be closed as off-topic because questions seeking debugging help ... etc. – Iharob Al Asimi Jun 05 '15 at 13:59

0 Answers0