C Programming - Role of spaces in scanf()

2019-08-05 00:19发布

问题:

I wrote the following code:

#include <stdio.h>
int main()
{
  int a, b;
  printf("Enter values of a and b\n");
  scanf(" %d%d ", &a, &b); // Note the two spaces before and after %d
  //     ^This^
  printf("a = %d b = %d\n", a, b);
  return 0;
}

The program run something like this:

aps120797@XENON-PC:/mnt/d/Codes/LetUsC$ ./a.out
Enter values of a and b
1
2
3
a = 1 b = 2

My question is that why is it taking three inputs instead of two (two %d is in scanf() ) and even if it is taking three, why is it skipping the last one?

回答1:

Space in a format string means to skip over any sequence of whitespace (spaces, newlines, tabs) in the input, and stops scanning when it gets to the first non-white character or the end of the input. That next character is left in the input buffer, so it can be read by the next format operator (if there is one) or the next input operation (if you were to call getc() after your scanf(), it would read the '3' character.

When you put a space at the end of the format string, it skips over the newline after 2, and keeps scanning until it gets to the next non-white character. So it has to get to the 3 before it stops.



标签: c scanf