Doesnt \n remain in the buffer?

55 Views Asked by At

Why does the program work fine when I use only integers? After I insert a number for variable 'a' and then press enter, doesn't \n remain in the buffer? If it indeed remains, then why can I initialize b also? If I had defined b as a char then the b output would b 10; in other words, the null newline character. If, for example, I wanted to enter a name many times for a number of the people using (using what?), would I have any problem? Do I need a function that clears the buffer? So what's wrong and how can I solve this problem

#include <stdio.h>

int main() {
   int a,b;
   
  printf("a ");
  scanf("%d",&a);
  printf("a=%d",a);
  
  printf("\nb ");
  scanf("%d",&b);
  printf("b=%d",b);
    return 0;
}
2

There are 2 best solutions below

1
Eric Postpischil On

For most of its conversions, including %d, scanf starts by reading and ignoring initial white-space characters, including the new-line character. Only for the conversions with [, c, or n does it not skip white-space characters.

To tell scanf to skip white-space characters before processing %c, insert a space in the format: scanf(" %c", &b);.

0
Some programmer dude On

Most scanf formats will read and discard leading white space (e.g. space, tab, and newline).

So, in the shown code, the newline will be left after the first call to scanf. But the second call to scanf will read and discard it. However, the newline after that input will be left in the input buffer.

The only three scanf formats that do not read and discard leading white space are %c, %[…] (scan sets) and %n. If you want the same behavior for those formats, you need to add an explicit leading space in the format string yourself.


Because error handling and invalid input could be hard to handle with scanf, I always recommend using fgets to read a whole line instead. Then, you can use, e.g. sscanf to parse the line.

This way, if there's invalid input, it will not be left in the input buffer.