当我更改输入顺序时,为什么我的程序不工作?

Why is my program not working when I change the order of inputs?

我开始学习 C 并尝试使用 switch 语句编写这个数学程序。当我先扫描运算符然后扫描数字时,程序 运行s 和工作正常。但是,如果我将 scanf 函数的顺序切换为先获取数字,然后再获取运算符,程序会获取数字,但之后它不会接受第二个输入(运算符),而只打印默认值(无效输入)。为什么会这样?

我已经提供了代码(如果我 运行 这段代码,问题出现在程序只取数字而不取运算符。但是顺序被翻转,它有效)。

#include <stdio.h>

int main()
{

    float a, b, result;
    char operator;

    printf("Enter 2 numbers:");
    scanf("%f %f", &a, &b);
    printf("Choose a math operator (+, -, *, /):");
    scanf("%c", &operator);

    switch (operator)
    {
    case '+':
        result = a + b;
        break;
    case '-':
        result = a - b;
        break;
    case '*':
        result = a * b;
        break;
    case '/':
        result = a / b;
        break;
    default:
        printf("\nInvalid operator");
        return -1;
    }
    printf("%f", result);
    return 0;
}

你需要改变

scanf("%c", &operator);

scanf("%s", &operator);

会运行。

格式字符串"%c"将从输入的第一行开始读取换行符。你想要的是 " %c" 它将跳过前导空格,所以替换行

scanf("%c", &operator);

scanf(" %c", &operator);

另见 https://pubs.opengroup.org/onlinepubs/9699919799/

A directive composed of one or more white-space characters shall be executed by reading input until no more valid input can be read, or up to the first byte which is not a white-space character, which remains unread.