Think what the user is doing. He types a number and then what? He hits enter! That is newline, which gets inserted in the stdin buffer, awaiting to be read by your program.
So when you try to read characters, the newline which is stored from before gets, which explains the behavior you are witnessing.
There is no need to cast ch
to check for the newline in the inner loop. Moreover, the inner loop would be better as a do-while loop.
getchar()
returns an int, not a char, so I would change this, and take into account EOF too. Read more in I'm trying to understand getchar() != EOF.
As Ed Heal pointed out, you could take advantage of the return value of scanf()
to to ensure that it has read an integer.
I would change your while-loop to this:
int ch;
while ( T-- )
{
if(scanf("%d", &N) != 1) // read the integer and check the return value
{
printf("I was expecting to read an integer! Exiting...\n");
return 1;
}
ch = getchar(); // consume the newline
printf("N is %d\n",N );
do {
ch = getchar(); // read the string char by char
printf("%c", ch); // while printing every char
} while (ch != '\n' || ch == EOF); // until you see the newline
}
Output:
Georgioss-MacBook-Pro:~ gsamaras$ gcc -Wall main.c
Georgioss-MacBook-Pro:~ gsamaras$ ./a.out < input.txt
N is 7
cookie milk milk cookie milk cookie milk
N is 5
cookie cookie milk milk milk
N is 4
milk milk milk milk
N is 1
cookie