scanf()/cin works but getchar() doesn't while taking strings as input

Hi. I recently found 3 problems in which we had to input multiple strings, separated by spaces and/or return(supposedly). But taking input 1 character at a time using the getchar() function gives WA, while scanf() or cin works.

Is this a test case defect, or am I doing it wrong?

Take these solutions for instance:

Using getchar(): [http://www.codechef.com/viewsolution/1771037][1]

Using cin: [http://www.codechef.com/viewsolution/1771063][2]

Thanks.
[1]: http://www.codechef.com/viewsolution/1771037
[2]: http://www.codechef.com/viewsolution/1771063

@jbuptit getchar() is line buffered… it needs to encounter key to terminate reading from stdin… while in cin and scanf() stop taking input when white space or is encountered…

hence scanf() and cin works here. n getchar do not :slight_smile:

if you want to check it just type following code.

char c;
while((c=getchar())!=EOF)
       printf("%c",c);

this code for a layman should print c at the exact time it was entered… but the output will be printed when you press enter…

Input will be of this format.

hello <enter>
hello

getchar() will keep reading character but will not take any action on it until terminated by a newline…

hope that will help

2 Likes
//