nidhi
nidhi

Reputation: 37

How to handle the extra newline character in stdin

Consider the following program :

#include<stdio.h>

int main(){

char c;
printf("Want to continue? :");
scanf("%c",&c);
while(c=='y')
  {
      printf("Want to continue? :");
      scanf("%c",&c);
  }
return 0;
}

What was wanted here is that the program continues till the user keeps on entering the character y.
But it exits after the first iteration even if the user enter y. As per my understanding, this is
happening because when I type y I also enter a new line and so the next time scanf will fetch this
newline character instead of the character that I typed.
One way to avoid this is simply use getchar() after each scanf so it simply eats up the new line
character. Is there any better alternative to it?

Upvotes: 1

Views: 575

Answers (1)

anotherOne
anotherOne

Reputation: 1573

Just add a space before the character to read.

scanf(" %c",&c);

Putting it after can cause troubles: What is the effect of trailing white space in a scanf() format string?)

EDIT: to answer your question about why it works. Well because that's just the way scanf has been built. In this page http://www.cplusplus.com/reference/cstdio/scanf/ you can read:

Whitespace character: the function will read and ignore any whitespace characters encountered before the next non-whitespace character (whitespace characters include spaces, newline and tab characters -- see isspace). A single whitespace in the format string validates any quantity of whitespace characters extracted from the stream (including none).

Upvotes: 1

Related Questions