-1

I am trying to work out why the second scanf is not working for me. Here is the code:

#include <stdio.h>
int main() {
     char n;int p;
     printf("Enter the number: ");
     scanf("%d",&p);
     if(p==1) {
          printf("Enter a character: ");
          scanf("%c",&n);
     }
}

In this program the second scanf("%c",&n) is not working. What am I doing wrong? The output of above program is:

Enter a number: 1
Enter a charter: 

It is coming out of compiler.

halfer
  • 19,824
  • 17
  • 99
  • 186
Ramana Uday
  • 355
  • 2
  • 6
  • 21

2 Answers2

1

It's because the previous scanf() left a newline in the input buffer. A simple fix to tell scanf to ignore all the whitespaces:

scanf(" %c",&n); //Note the space before %c

Any whitespace directive ( space, \n etc) in the format string tells scanf ignore any number of whitespaces in the input.

From scanf() manual:

   A sequence of white-space characters (space, tab, newline,
          etc.; see isspace(3)).  This directive matches any amount of
          white space, including none, in the input.
P.P
  • 117,907
  • 20
  • 175
  • 238
  • Dude thank for that but what is the space doing there ? – Ramana Uday Dec 02 '15 at 17:48
  • 2
    A whitespace in the format string means `scanf()` will ignore all whitespaces in the input. You can use any whitespace character for the same effect, not necessarily *space*. There are other ways to achieve the same such as reading all chars from stdin using `getchar()` in a loop. My general suggestion is to avoid `scanf()` whenever possible. Instead use `fgets()` to read a line and use `sscanf()` to parse the line as necessary. – P.P Dec 02 '15 at 17:50
1

The previous scanf() leaves a trailing newline character \n. Eat it by doing

scanf(" %c",&n);
Haris
  • 12,120
  • 6
  • 43
  • 70