c - Reading multiple user input strings inside a loop -



trying solve problem codechef having troubles using fgets() inside loop.

the first input (t) going positive integer containing number of user inputs.
delimited newline characters, user going input string below length of 10 under circumstances.

so, i've tried this:

#include <stdio.h> #include <stdlib.h>  #define size 10  int main() {     int t;     int diffx, diffy;     char s[size];      scanf("%d", &t);      while (t--){         fgets(s, size, stdin);         printf("%s\n", s);     }     return 0; } 

however, when attempted test code following inputs:

3
hello
hi
what

i able input until "hi" program exited (returning 0).

why case , how can fix it?

thank in advance,
kpark.

fgets() consumes newline left behind first call scanf(). so, consuming 3 lines, first line looks empty line fgets() loop have.

you can fix using fgets() first line too, , parse string number using sscanf().

fgets(s, size, stdin); sscanf(s, "%d", &t); /* ... */ 

Comments

Popular posts from this blog

Detect support for Shoutcast ICY MP3 without navigator.userAgent in Firefox? -

web - SVG not rendering properly in Firefox -

java - JavaFX 2 slider labelFormatter not being used -