Monday, 19 August 2013

Reading multiple user input strings inside a loop

Reading multiple user input strings inside a loop


I am currently trying to solve a problem from CodeChef but I am having
troubles with using fgets() inside a loop.

The first input (T) is going to be a positive integer containing the
number of user inputs.
Then delimited by newline characters, the user is going to input a string
below the length of 10 under any 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 I attempted to test the code with the following inputs:
3
Hello
Hi
What

I was only able to input until "Hi" then the program exited successfully
(returning 0).

Why is this the case and how can I fix it?
Thank you in advance,
kpark.

No comments:

Post a Comment