C: Multiple scanf's, when I enter in a value for one scanf it skips the second scanf

Snow_Mac picture Snow_Mac · Mar 5, 2012 · Viewed 92.5k times · Source

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?

Answer

Thomas Padron-McCarthy picture Thomas Padron-McCarthy · Mar 5, 2012

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").