getchar not working in switch case (c)

Stumbler picture Stumbler · Nov 19, 2012 · Viewed 7.5k times · Source

Using a very simple calculator program that prompts a user for an operation to perform, followed by a prompt for two integers on which to perform this operation. The program is supposed to loop after these operations, except in the case where the user enters the character 'q', at which point the program is supposed to quit.

#include <stdio.h>

int main (void)
    {
        char c;
        int number[2], num1, num2, result;
        double num1d, num2d, resultd;
        int done=1;

        while(done)
        {
        printf("\t What sort of operation would you like to perform? \n \t Type + - * / accordingly. \n");
        c = getchar();
        printf("\tplease enter a number \n");
        scanf("%d",&number[0]);
        printf("\tplease enter another number \n");
        scanf("%d",&number[1]);
        num1 = number[0];
        num2 = number[1];

        switch(c)
            {
            case('-'):
            result = num1-num2;
            printf("\nThe first number you entered subtracted by the second number is %d.\n", result);
            break;

            case('+'):
            result = num1+num2;
            printf("The first number you entered added to the second number is %d.\n", result);
            break;

            case('*'):
            result = num1*num2;
            printf("The first number you entered multiplied with the second number is %d.\n", result);
            break;

            case('/'):
            num1d = (double) num1;
            num2d = (double) num2;
            resultd = num1d/num2d;
            printf("The first number you entered divided by the second number is %g.\n", resultd);;
            break;

            case('q'):
            printf(" Now Exiting...\n");
            done=0;
            break;

            default:
            puts("Invalid key pressed. Press q to exit");
            break;
            }
        }

        return 0;
    }

Works correctly for a single calculation, but subsequently performs oddly; in particular it prints

printf("\t What sort of operation would you like to perform? \n \t Type + - * / accordingly. \n");
printf("\tplease enter a number \n");

altogether.

The standard method of clearing the input buffer while (getchar() != '\n'); doesn't fix this. One out of two times that this text displays incorrectly the user can still use the program as if the instructions were displaying as they should (so the user can type an operation such as +, carriage return, and then some integer and a carriage return, and the program will perform correctly from that point on) Every other time however the program will put "Invalid key pressed. Press q to exit" regardless of input.

Answer

Mike picture Mike · Nov 19, 2012

What everyone else here is saying is true, getchar() returns an int but that's not your problem.

The problem is that getchar() leaves a newline character after you use it. If you're going to use getchar() you must always consume the newline char afterwards. This simple fix:

   printf("\t What sort of operation would you like to perform? \n \t Type + - * / accordingly. \n");
    c = getchar();
    getchar();     //<-- here we do an extra getchar for the \n
    printf("\tplease enter a number \n");
    scanf("%d",&number[0]);
    printf("\tplease enter another number \n");
    scanf("%d",&number[1]);

and that will eliminate the problem. Every time you type <somechar><enter> it's really putting two characters on the buffer, for example if I hit + and enter I'm getting:

'+''\n'  // [+][\n]

getchar() will only get the first of these, then when getchar() is called again it won't wait for your input it will just take that '\n' and move on to the scanf()