1

Today I encountered with problem that when I use twice scanf which accept character as input then second scanf skipped.

I tried to figure out I came to the conclusion that when we press enter key after first scanf the second scanf is skipped because enter key is take as input in the second scanf.

Can some please explain what is the exact reason with it?

int main()
{
     char ch;
     int num;
     scanf("%d",&num);
     scanf("%c",&ch);//This is skipped but its accept input when space as scanf(" %c",&ch) 
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
BECOOL
  • 203
  • 1
  • 3
  • 11

1 Answers1

1
scanf("%c", &ch);

It will read '\n' from the previous scanf since you are inputting a number and pressing enter, if you don't write it like scanf(" %c", &ch);. That way it will ignore '\n' and wait until you enter a valid char.

Survaf93
  • 162
  • 1
  • 11