c++ - Can't get a top element of the filled stack
问题描述
I stuck with stack) In this code I'n filling few stacks and later trying to get a date from them. But with char stack I got a problem-error.
Declared stack in the header
stack<int> numbers;
stack<char> operators;
Input method
void Notation::InptWriter() {
notationPtr = new char[SIZE];
cout << "Enter expression: ";
cin.getline(notationPtr, SIZE);
}
This method for filling up the stacks(1 for integers,1 for char)
void Notation::Convert(char *ptr, int *store) {
int x = 0;
static string y = "";
for (int i = 0; i < strlen(ptr); i++) {
if (isdigit(*(ptr + i))) { //for numbers greater that 9
y += *(ptr + i);
} else { // if inline char isNaN push char to Operator stack, then convert 'y' to int and push to number stack
operators.push(*(ptr + i));//push value to the stack
if (y != "") {
x = stoi(y);
numbers.push(x);
y = "";
}
}
if (!operators.empty()) {
cout << "op: " << operators.top();
}
if (!numbers.empty()) {
cout << "__Num: " << numbers.top();
}
cout << "----" << *(ptr + i) << "---" << y << endl;
}
}
Here I try to initialize the variable with the same data type from the stack and get an error during runtime
void Notation::StackWorking(stack<int> nums, stack<char> opers) {
char op;
int num;
cout<<operators.top()<<" "<<numbers.top();
while (!opers.empty() && !nums.empty()){
cout<<"in";
op = operators.top();//Problem over there
operators.pop();
num = numbers.top();
numbers.pop();
cout << op << " " << num << endl;
}
Thank you!
I commended a lines where I look on top of the stack and everything start to work...
if (!operators.empty()) {
// cout << "op: " << operators.top();
}
if (!numbers.empty()) {
// cout << "__Num: " << numbers.top();
but i still don't know why...
解决方案
It looks like you are using the wrong variable, In the while you you test opers
ans nums
while (!opers.empty() && !nums.empty()){
where as in the loop you use operators
and numbers
op = operators.top();//Problem over there
operators.pop();
num = numbers.top();
numbers.pop();
see working example here
推荐阅读
- java - pom.xml 中需要 Maven 依赖项,用于从 alfresco 下载文档
- javascript - Web3.js 的问题,尝试调用他的合同来查看状态
- c++ - istringstream split_string(line) 如何在不使用 while 循环的情况下在换行时更新 split_string?
- javascript - 如何使带有输入框的滑块反应钩子
- python - 将 Outlook 电子邮件转换为 PDF
- c - 将一个数组的元素复制到另一个数组中。找不到我的错误
- sql - 如何将sql执行结果返回到bat文件
- python - python socketserver如何向外传递变量?
- node.js - 从我的 express 服务器渲染我的 React 应用程序有什么好处吗?
- excel - 如何将同一列中的值复制到下一列?Excel VBA