26

I have this block of code (functions omitted as the logic is part of a homework assignment):

#include <stdio.h>

int main()
{
    char c = 'q';
    int size; 

    printf("\nShape (l/s/t):");
    scanf("%c",&c);

    printf("Length:"); 
    scanf("%d",&size);

    while(c!='q')
    {
        switch(c)
        {
            case 'l': line(size); break; 
            case 's': square(size); break;
            case 't': triangle(size); break; 
        }


        printf("\nShape (l/s/t):");
        scanf("%c",&c);

        printf("\nLength:"); 
        scanf("%d",&size);
    }

    return 0; 
}

The first two Scanf's work great, no problem once we get into the while loop, I have a problem where, when you are supposed to be prompted to enter a new shape char, it instead jumps down to the printf of Length and waits to take input from there for a char, then later a decimal on the next iteration of the loop.

Preloop iteration:

Scanf: Shape. Works Great
Scanf: Length. No Problem

Loop 1.

Scanf: Shape. Skips over this
Scanf: length. Problem, this scanf maps to the shape char.

Loop 2
Scanf: Shape. Skips over this
Scanf: length. Problem, this scanf maps to the size int now.

Why is it doing this?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Snow_Mac
  • 5,727
  • 17
  • 54
  • 80

7 Answers7

46

scanf("%c") reads the newline character from the ENTER key.

When you type let's say 15, you type a 1, a 5 and then press the ENTER key. So there are now three characters in the input buffer. scanf("%d") reads the 1 and the 5, interpreting them as the number 15, but the newline character is still in the input buffer. The scanf("%c") will immediately read this newline character, and the program will then go on to the next scanf("%d"), and wait for you to enter a number.

The usual advice is to read entire lines of input with fgets, and interpret the content of each line in a separate step. A simpler solution to your immediate problem is to add a getchar() after each scanf("%d").

Stefan van den Akker
  • 6,661
  • 7
  • 48
  • 63
Thomas Padron-McCarthy
  • 27,232
  • 8
  • 51
  • 75
  • 4
    The `scanf("%d"); getchar();` combination fails if the user accidentally enters a space (or other garbage) after the number. – ilkkachu Jun 11 '17 at 10:14
25

The basic problem is that scanf() leaves the newline after the number in the buffer, and then reads it with %c on the next pass. Actually, this is a good demonstration of why I don't use scanf(); I use a line reader (fgets(), for example) and sscanf(). It is easier to control.

You can probably rescue it by using " %c" instead of "%c" for the format string. The blank causes scanf() to skip white space (including newlines) before reading the character.

But it will be easier in the long run to give up scanf() and fscanf() and use fgets() or equivalent plus sscanf(). All else apart, error reporting is much easier when you have the whole string to work with, not the driblets left behind by scanf() after it fails.

You should also, always, check that you get a value converted from scanf(). Input fails — routinely and horribly. Don't let it wreck your program because you didn't check.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
7

Try adding a space in the scanf.

scanf(" %d", &var);
//     ^
//   there

This will cause scanf() to discard all whitespace before matching an integer.

Toby Speight
  • 27,591
  • 48
  • 66
  • 103
Jon Z.
  • 121
  • 3
  • 8
  • 2
    According to [section 7.21.6.2p8](http://port70.net/~nsz/c/c11/n1570.html#7.21.6.2p8), `scanf` would *normally* discard all whitespace before matching an integer, anyway, rendering the whitespace in this format string pointless: *"Input white-space characters (as specified by the isspace function) are skipped, unless the specification includes a [, c, or n specifier."* – autistic Feb 21 '17 at 02:14
  • 2
    This won't fix the issue. `%d` already skips leading whitespace characters. – Spikatrix Feb 21 '17 at 02:43
6

Use the function

void seek_to_next_line( void )
{
    int c;
    while( (c = fgetc( stdin )) != EOF && c != '\n' );
}

to clear out your input buffer.

Mathieu K.
  • 283
  • 3
  • 14
noMAD
  • 7,744
  • 19
  • 56
  • 94
  • 1
    This is a good function. For readability, I would put the null statement (the single semicolon) on a separate line. – Thomas Padron-McCarthy Mar 05 '12 at 06:45
  • 1
    I also like this, but I think it'd be best *not* to use the word "flush", as this has an established definition within the standard which contradicts the use here. Perhaps `seek_to_next_line` would be a more descriptive name? – autistic Feb 21 '17 at 02:11
  • Making @Sebivor's proposed change. – Mathieu K. Mar 24 '18 at 22:09
  • Also putting this here since I can't add my own answer, and this is the best answer I see: `scanf("%*[^\n]"); getchar();`. You can wrap this into a function, if you like. There's no benefit over this answer; both are technically fine, though the answer is easier to maintain, which is sort of a double-edged sword in this case; usually we trend towards writing more maintainable code but with idiots about the simpler version might be more likely to be modified to something incorrect... you know what I'm talking about... a certain *optimisation*. Choose the correct tool per job, right? – autistic Mar 25 '18 at 12:38
2

The '\n' character is still left on the input stream after the first call to scanf is completed, so the second call to scanf() reads it in. Use getchar().

Stefan van den Akker
  • 6,661
  • 7
  • 48
  • 63
Gargi Srinivas
  • 929
  • 6
  • 6
1

When you type the shape and ENTER, the shape is consumed by the first scanf, but the ENTER is not! The second scanf expects a number so, the ENTER is skipped because is considered a white space, and the scanf waits for a valid input ( a number) that, again, is terminated by the ENTER. Well, the number is consumed, but the ENTER is not, so the first scanf inside the while uses it and your shape prompt is skipped... this process repeats. You have to add another %c in the scanfs to deal with the ENTER key. I hope this helps!

guga
  • 714
  • 1
  • 5
  • 15
0

You can also use scanf("%c%*c", &c); to read two characters and ignore the last one (in this case '\n')

Byeonggon Lee
  • 196
  • 10
  • People do the darnedest things — like putting spaces after the main input. Any single character scanner like this is fragile at best. – Jonathan Leffler Oct 31 '22 at 21:55