c获得没有空格的下一个字符

时间:2014-10-13 08:40:27

标签: c

我需要以下代码的帮助。程序进行简单的算术计算。问题是2(空格)+3工作正常,但2 + 3没有读取运算符。如何在没有空间的情况下使其工作? getchar和putchar是必须的,没有字符串函数。该程序将提取2个操作数和操作符,执行指示的计算并显示结果。提前谢谢。

while ((ch = getchar()) != EOF)  /*Begining of the while loop*/
{
    if ((status == first)) {  
        if ((ch >= '0') && (ch <= '9'))
        {
            num1 = ((num1 * 10) + (ch - '0'));
        }
        else status = operand;
    }
    else if (status == operand)
    {
        if (ch == '+' || ch == '-' || ch == '*' || ch == '/' || ch == '%'){
            /*count++;*/
            oper = ch;
            /*printf("Count %d \n", count);
        }
        else if (count>1){  // This opening brace was missing
            printf("Operator Error.\n");*/
            status = second;
        }
    }
    else if ((status == second) && ((ch >= '0') && (ch <= '9'))){
        num2 = ((num2 * 10) + (ch - '0'));
    }
}

2 个答案:

答案 0 :(得分:0)

while ((ch = getchar()) != EOF){
    if ((status == first)) {  
        if ((ch >= '0') && (ch <= '9')) {
            num1 = ((num1 * 10) + (ch - '0'));
        } else
            status = operand;//already read one char. or use ungetc  E.g.{ status = operand; ungetc(ch, stdin); }
    }
    if (status == operand) {
        if (ch == '+' || ch == '-' || ch == '*' || ch == '/' || ch == '%'){
            oper = ch;
            status = second;
        }
    } else if ((status == second) && ((ch >= '0') && (ch <= '9'))){
        num2 = ((num2 * 10) + (ch - '0'));
    }
}

答案 1 :(得分:0)

这省略了状态变量并检查是否已分配操作数以确定数字是用于num1还是num2。在else中消耗非数字,如果它们是有效的操作数,则分配操作数。输入在EOF或&#39; \ n&#39;

上停止
#include<stdio.h>
#include<stdlib.h>

int main() {
    int num1 = 0;
    int num2 = 0;
    int ch = 0;
    char operand = 0;

    while (((ch = getchar()) != EOF) && ch != '\n') {
        if ((ch >= '0') && (ch <= '9')) { // digits
            if (operand == 0) {
                num1 = ((num1 * 10) + (ch - '0')); // no operand so use num1
            }
            else {
                num2 = ((num2 * 10) + (ch - '0')); // operand has been assigned
            }
        }
        else { // non digits
            if (ch == '+' || ch == '-' || ch == '*' || ch == '/' || ch == '%'){
                if ( operand == 0) { // do not re-assign operand
                    operand = ch; // assign operand
                }
            }
        }
    }
    printf ( "num1 %d operand %c num2 %d\n", num1, operand, num2);
    return 0;
}

这也可能起作用而不是上面的while循环 %d读取整数
%1 [ - + / *%]读取必须是有效操作数之一的单个字符。 %1跳过任何空格(如果存在)之前的空格 %d读取另一个整数
如果scanf成功读取了三个值,则会打印它们。

char operand[2] = {0};
if ( ( scanf ( "%d %1[-+/*%] %d", &num1, operand, &num2)) == 3) {
    printf ( "num1 %d operand %c num2 %d\n", num1, operand[0], num2);
}