C 编程 : getchar() won't accept '+' or '-' for input, 但会接受 '*' 和 '/' 吗?

标签 c calculator getchar

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

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

我把它当作一个 float ,然后我得到char。这可能是问题所在吗?

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

关于C 编程 : getchar() won't accept '+' or '-' for input, 但会接受 '*' 和 '/' 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37633921/

相关文章:

java - 我正在使用 Java 构建计算器,但在执行运算符时遇到问题

Python:获取按键事件并输出其他内容

c - 使用后明确清除/归零敏感变量是否明智?

c - 如何优化 C 中围绕零对称的整数区间的范围检查?

java - 希望添加一个计算器来计算食品应用程序今天的卡路里

C getchar() 刽子手游戏

c - 错误 : A label can only be part of a statement

c - openGL ES 2 - 有没有办法附加分辨率与目标纹理不同的模板缓冲区?

c - 编写原型(prototype)而不是#include <stdio.h>

objective-c - 在 Xcode 中收到 "Control reaches end of non-void function"错误消息