1

When I use scanf to get two input values like below, I find that when I enter two values, like 1 2, the program doesn't continue, it gets stuck.

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    int a = 0, b = 0;

    scanf("%d %d ", &a, &b);
    printf("%d\n%d\n", a, b);
    system("pause");

    return 0;
}

The only way the code works is if I input 1 2 1.The last 1 can be any valid character other than a space, TAB, or carriage return.

I found the reason of the problem is an extra blankspace in the line of scanf. So if I change the line like this, it works fine. But I don't understand why. Please explain this.

scanf("%d %d", &a, &b);
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
joe
  • 11
  • 2
  • Please remove the final space (which must match whitespace in the input), so it's `scanf("%d %d", &a, &b);`. It filters *any amount* of whitespace, so it doesn't complete until a non-whitespace character appears (the third entry) – Weather Vane Nov 14 '21 at 07:39
  • ...you are usually on a hiding to nowhere trying to filter trailing whitespace. Concentrate on *leading* whitespace. The format specifiers `%d` and `%s` and `%f` automatically filter leading whitespace characters, but `%c` and `%[]` and `%n` do not, and you can instruct `scanf` to do so by adding a space just *before* the `%`. – Weather Vane Nov 14 '21 at 07:49
  • Note too that newlines are simply 'white space characters' to `scanf()` et al. It won't stop scanning because you hit return. It will stop scanning when it comes across something that isn't a white space character — which means the start of the next entry. Knowing what to type next requires prescience on the part of the program user. Consequently, it is a bad idea to use trailing white space in a `scanf()` format string — doubly so if a human and not a file or computer is expected to provide the data. – Jonathan Leffler Nov 14 '21 at 07:55

0 Answers0