C 编程:getchar() 不接受“+”或“-”作为输入,但会接受“*”和“/”?

C Programming: getchar() won't accept '+' or '-' for input, but will accept '*' and '/'?

我正在尝试从输入中收集操作数 (+,-,*,/)。当我尝试这样做时,* 和 / 输入被接受,并且代码有效。当我输入 + 或 - 时,会抛出默认异常。

这是怎么回事?! getchar 中的 + 或 - 符号是否存在某种问题?我可以尝试根据 ascii 值引用它吗?

我把它作为一个浮点数接受,然后我得到一个字符。这可能是问题所在吗?

float result = 0.0;
float userEntry = 0.0;
char getOperand;

void main(){

printf("Calculator is on\n");
printf("Initial value is 0.0, please issue an operation in the following format: ex. +5 -5 *5 or /5. Do not add more than one number to the total.\n");
scanf("%3f", &userEntry);
getOperand = getchar();
printf("%f", userEntry);
putchar(getOperand);

switch(getOperand){

    case '+':
        printf("addition\n");
        break;
    case '-':
        printf("subtraction\n");
        break;
    case '/':
        printf("division\n");
        break;
    case '*':
        printf("multiplication\n");
        break;
    default:
        printf("UnknownOperatorException is thrown.\n");
        break;

    }
}

问题是 +5 和 -5 被 scanf 函数读取为 5 和 -5,getchar 函数没有任何内容可以读取。 / 和 * 不被具有给定格式的 scanf 识别,并且一旦达到这些就停止读取,将它们留给 getchar.

相反,您可以尝试在调用 scanf 之前调用 getchar

这是它工作的一个例子,只需将调用切换到 scanfgetchar 周围:

http://ideone.com/Jlx7II

输入:

+5

输出:

Calculator is on
Initial value is 0.0, please issue an operation in the following format: ex. +5 -5 *5 or /5. Do not add more than one number to the total.
5.000000+addition

为了防止 operand 被解释为 sign,一个带有额外参数的 scanf() 调用也可以使用:

scanf(" %c%3f", &getOperand, &userEntry);//leading space instructs trailing '\n's consumed

根本不需要调用 getchar()

用于添加 -1 的打印输出:

Calculator is on
Initial value is 0.0, please issue an operation in the following format: ex. +5 -5 *5 or /5. Do not add more than one number to the total.
+-1
-1.000000+addition