Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scanf doesn't return when pressing enter

I spent the past hour trying to figure out why

char buffer[101];
scanf("%100[^\n]", buffer);

works as intended, reading a string until in encounters a newline, while

char buffer[101];
scanf("%100[^\n]\n", buffer);

does not return after pressing Enter.

Explicitly flushing the input buffer with CtrlD (in linux) immediately after pressing Enter seems to fix the problem, forcing the scanf to return. Am I missing something here?

like image 843
Veritas Avatar asked May 02 '26 14:05

Veritas


1 Answers

Yes, you have missed an important detail that's well documented. According to the scanf manual...

A directive composed of one or more white-space characters shall be executed by reading input until no more valid input can be read, or up to the first byte which is not a white-space character, which remains unread.

This implies that scanf will indeed not return when you press enter; It'll continue waiting to see if you press enter (or space, or tab) again... and again... until it sees something that isn't white-space.

If you want to discard the '\n' that's left following the scanset directive, you could use %*c like so: int x = scanf("%100[^\n]%*c", buffer);...

P.S. Don't forget to check the value of x. It's particularly important when you use scanset directives, because an empty line will result in an uninitialised buffer, in this case.

like image 150
autistic Avatar answered May 04 '26 03:05

autistic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!