C编程:getchar()不接受' +'或者' - '输入,但会接受' *'和' /'?

时间:2016-06-04 19:00:16

标签: c calculator getchar

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

发生了什么事?! getchar中的+或 - 符号是否存在某种问题?我可以尝试针对ascii值引用它吗?

我把它作为一个浮点数,然后我getchar。这可能是问题吗?

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;

    }
}

2 个答案:

答案 0 :(得分:3)

问题在于scanf函数将+5和-5读为5和-5,getchar函数无需读取任何内容。 scanf无法使用给定格式识别/和*,一旦达到这些格式就会停止阅读,将其留给getchar

相反,您可以在致电getchar之前尝试拨打scanf

通过简单地将呼叫切换到scanfgetchar,以下是其工作的示例:

http://ideone.com/Jlx7II

输入:

+5

Ouptut:

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

答案 1 :(得分:2)

为防止操作数被解释为 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