Home>

C scanf is not executed.

I created a sample code (list_03.5.c) for the switch statement.
scanf ("% c" ;,&kigou);
Part is not executed? Does not accept symbol input.

How does this work?
And how do you isolate and solve it?
Is there a useful option to make it easier to find bugs at compile time or run time?

# include<stdio.h>
int main ()
{
    int a, b, answer;
    char kigou;
    printf ("Enter two numbers and calculate [sum | difference | product | quotient] \ n");
    printf ("Please enter the first number. \ n");
    scanf ("% d",&a);
    printf ("Please enter the second number. \ n");
    scanf ("% d",&b);
    printf ("Please enter the symbol [+ |-| * | /] \ n");
    scanf ("% c",&kigou);// processing is skipped !?
    printf ("debug \ n");
    switch (kigou) {
        case '+':
            answer = a + b;
            printf ("% d% c% d =% d. \ n", a, kigou, b, answer);
            break;
        case '-':
            answer = a-b;
            printf ("% d% c% d =% d. \ n", a, kigou, b, answer);
            break;
        case '*':
            answer = a * b;
            printf ("% d% c% d =% d. \ n", a, kigou, b, answer);
            break;
        case '/':
            answer = a/b;
            printf ("% d% c% d =% d. \ n", a, kigou, b, answer);
            break;
        default:
            printf ("Please enter the correct symbol \ n");
            break;
    }
    return 0;
}

[hoge @ hoge] # gcc list_03.5.c
[hoge @ hoge] # ./a.out
Enter two numbers and calculate [sum | difference | product | quotient].
Enter the first number.
8
Enter the second number.
2
Enter the symbol [+ |-| * | /].
debug
Enter the correct symbol.

c
  • Answer # 1

    Because you are pressing Enter with the previous number input, the next% cwill enter Enter or\ n.

    Beginners should not usescanf. Replace withfgets+sscanf.

    char line [100];
    ~~
    fgets (line, sizeof line, stdin);
    sscanf (line, "% d",&a)
    ~~
    fgets (line, sizeof line, stdin);
    sscanf (line, "% d",&b)
    ~~
    fgets (line, sizeof line, stdin);
    sscanf (line, "% c",&kigou)
    ~~

    Although omitted, originallyfgets,sscanf, and naturallyscanfneed to be checked.

  • Answer # 2

    I don't think it's not loaded.
    Probably the line break after the numeric input is read.

    If you want to skip blank characters such as line breaks,
    scanf ("% c" ;,&kigou);
    If you put a space character before% c like this, it will be skipped.