0

Why is it that when I use a space before the format specifier in scanf() the program works fine. Code below:

printf("What's your username: ");
scanf(" %s", username);

printf("Do you want to make a deposit or a withdrawal? [d/w]\n");
scanf(" %c", &choice);

When I don't have a space like this code below, it exits:

printf("What's your username: ");
scanf("%s", username);

printf("Do you want to make a deposit or a withdrawal? [d/w]\n");
scanf("%c", &choice);

Is there a good explanation to this?

Klas Lindbäck
  • 33,105
  • 5
  • 57
  • 82
Dr Spec
  • 23
  • 4
  • 1
    I've seen at least a score questions that boils down to this very issue. Is there already a good canonical question for this? – Klas Lindbäck May 17 '16 at 11:06

2 Answers2

5

Yes there is a good explanation, and the explanation is that the newline you entered for the first input is still in the buffer when you try to read the character for the second input. Reading a single character using the "%c" scanf format will read the first character in the input buffer, no matter what it is.

By adding the leading space you tell scanf to read and discard all leading white-space.

Most formats do this automatically, for example the "%s" format, so you don't need the leading space in the format string there. Read e.g. this scanf (and family) reference for more information, and for which formats you need to explicitly skip leading space.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
1

This happens because scanf skips over white space when it reads data such as the integers or char. White space characters are those characters that affect the spacing and format of characters on the screen, without printing anything visible. The white space characters you can type as a user are the blank space (spacebar), the tab character (Tab key), and the newline (Enter Key). reference link here.

Community
  • 1
  • 1
msc
  • 33,420
  • 29
  • 119
  • 214