我一直在运行它并输入"12+"
表达式。'我试图添加最高值和下一个值,它一直给我结果'c'
,但我希望结果为 3。那么有什么方法可以让我的程序将 char 'c' 转换为 int '3' 和char 'd' 到 int 4 等等?
//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 (!isdigit(it))
{
cout << it << "!\n";
it = exp[count--];
}
STK.push(it);
cout << STK.topValue() << "\n";
it = exp[count - 2];
cout << it << "\n";
if (isdigit(it))
{
STK.push(it);
}
cout << STK.topValue() << "\n";
cout << STK.nextValue() << "\n";
it = STK.topValue() + STK.nextValue();
cout << it << "\n";
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);
}