为什么我的"while"条件没有得到满足?

Why is my "while" condition not being met?

本文关键字:满足 我的 while 条件 为什么      更新时间:2023-10-16

我一直在运行这个并输入"12+"作为表达式。当它到达while循环时,它就卡住了,好像条件从未满足过一样。我不明白为什么会这样,因为在while循环之前"it"等于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);
}

如您所述,您的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