Veritas
Veritas

Reputation: 2210

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?

Upvotes: 3

Views: 3326

Answers (1)

autistic
autistic

Reputation: 15642

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.

Upvotes: 5

Related Questions