1

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?

nidhi
  • 37
  • 6
  • 1
    Use `scanf(" %c",&c);` inside `while` – IrAM Dec 13 '20 at 19:49
  • Some explanation: most of the format specifiers for `scanf` automatically filter leading whitespace, but `%c` and `%[]` and `%n` do not. Adding a space in front of the `%` instructs `scanf` to filter leading whitespace here too. – Weather Vane Dec 13 '20 at 19:54
  • You could also ignore everything except `'y'` or `'n'`: `do scanf("%c", &c); while (c != 'y' && c != 'n');` – pmg Dec 14 '20 at 12:07

1 Answers1

1

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).

anotherOne
  • 1,513
  • 11
  • 20
  • Thanks that works. But I don't understand the difference between scanf("%c ",&c) and what you have mentioned. Although this does not work. What is the reason for it? – nidhi Dec 14 '20 at 11:10
  • @nidhi I made an edit to answer this question – anotherOne Dec 14 '20 at 12:05