为什么我的“同时”状况没有得到满足?

时间:2013-04-23 18:48:38

标签: c++ loops while-loop stack postfix-notation

我一直在运行这个并输入“12+”作为表达式。当它到达while循环时,它会被卡住,好像从未遇到过这种情况。我不明白为什么这是因为在while循环之前“它”等于2所以甚至不应该使用循环。

//array based stack implementation
class Stack
{
private:
    int capacity;        //max size of stack
    int top;            //index for top element
    char *listArray;       //array holding stack elements

public:
    Stack (int size = 50){ //constructor
        capacity = size;
        top = 0;
        listArray = new char[size];
    }

    ~Stack() { delete [] listArray; } //destructor


    void push(char it) {    //Put "it" on stack
        listArray[top++] = it;
    }
    char pop() {   //pop top element
        return listArray [--top];
    }

    char& topValue() const { //return top element
        return listArray[top-1];
    }

    char& nextValue() const {//return second to top element
        return listArray[top-2];
    }


    int length() const { return top; } //return length



};

int main()
{
    string exp;
    char it = ' ';
    int count;
    int push_length;


    cout << "Enter an expression in postfix notation:\n";
    cin >> exp;
    cout << "The number of characters in your expression is " << exp.length() << ".\n";
    Stack STK;

    for(count= 0; count < exp.length() ;count++)
    {

        if (exp[count] == '+')
        {
            it = exp[count - 1];
            cout << it << "\n";


            while (it != 1 || it != 2 || it != 3 || it != 4 || it != 5 || it != 6 || it != 7 || it != 8 || it != 9 || it != 0)
            {
                cout << it << "\n";
                it = exp[count--];
            }

            STK.push(it);
            //cout << STK.topValue() << "\n";

            it = exp[count --];
            if (it == 1 || it == 2 || it == 3 || it == 4 || it == 5 || it == 6 || it == 7 || it == 8 || it == 9 || it == 0){
                STK.push(it);
                cout << it;
            }
            cout << STK.topValue() << "\n";
            it = STK.topValue() + STK.nextValue();
            STK.pop();
            STK.pop();
            STK.push(it);
            cout << STK.topValue() << "\n";

        }


    }
    cout << "The number of characters pushed into the stack is " << STK.length() << ".\n";
    push_length = STK.length();



    return(0);
}

1 个答案:

答案 0 :(得分:6)

如您所述,您的while子句始终为true

while (it != 1 || it != 2 || it != 3 || it != 4 || it != 5 || it != 6 || it != 7 || it != 8 || it != 9 || it != 0)

it始终

可以将该语句中的每个||更改为&&,因为这可能就是您的意思。 并将1更改为'1',将2更改为'2',依此类推......

更明确的方法是:

while ( !std::isdigit(it) )

http://en.cppreference.com/w/cpp/string/byte/isdigit