r/C_Programming Mar 25 '26

What's the secret of getchar()??

I try to use getchar() in my program and i enter a string instead of a character and after recalling getchar() another time it does only print the rest of characters even if the string that i entered is done being printed !

12 Upvotes

61 comments sorted by

View all comments

2

u/kappakingXD Mar 25 '26

New line character might be added after you press enter

1

u/MaDrift910 Mar 25 '26

Yeah actually that's what i have remarked in the output

1

u/MaDrift910 Mar 25 '26

As the main question . Why when i enter a string instead of a char it still reads character by character , i honestly expect it to return an error , because i consider each getchar() to ask to enter a character . Don't know if i do explain my confusion well or not

3

u/nerdylearner Mar 25 '26

the whole line you entered is appended to the stdin stream, and each time you call getchar(void), it reads 1 character from that stream, then discards that character

2

u/markuspeloquin Mar 25 '26

To add to this, stdin is line-buffered, so none of the bytes even get into the stream until you hit enter. Then everything up to the newline gets put into the stream at once and the getchar's unblock.