[英]Where is my stack?, C++ stack STL
What I'm trying to do is reading from char array and separate char by number and operator. 我想做的是从char数组读取并按数字和运算符分隔char。 so, if input char is 1+2*3, output should be 123+* The problem is when I retrieve data from the stack, there isn't any type of char data inside the stack.
因此,如果输入char为1 + 2 * 3,则输出应该为123 + *问题是当我从堆栈中检索数据时,堆栈中没有任何类型的char数据。
#include <iostream>
#include <map>
#include <stack>
using namespace std;
void getOper(char* arr)
{
map<char, int> operTable;
stack<char> stk;
stack<char> num;
//setup table
operTable.insert(pair<char, int>( '*', 1 ));
operTable.insert(pair<char, int>( '/', 1 ));
operTable.insert(pair<char, int>( '+', 4 ));
operTable.insert(pair<char, int>( '-', 4 ));
operTable.insert(pair<char, int>( '(', 0 ));
operTable.insert(pair<char, int>( ')', 0 ));
//iterate through an input array
map<char, int>::iterator iter;
for(unsigned int i = 0; i < sizeof(arr) / sizeof(arr[0] ); i++)
{
//is input an operator?
map<char, int>::iterator iter = operTable.find(arr[i]);
if(iter != operTable.end()) //if input is operator
{
stk.push(arr[i]);
//cout << stk.top() << endl; //operator is saved into stack, check.
}
else //input is a number.
{
cout << arr[i];
}
}
while(!stk.empty())
{
cout << stk.top();
stk.pop();
}
}
int main()
{
char arr[] = "1+2*3";
getOper(arr);
return 0;
}
Don't use sizeof()
on char*
. 不要在
char*
上使用sizeof()
。
Better yet, use std:string
. 更好的是,使用
std:string
。
char * arr;
for(unsigned int i = 0; i < sizeof(arr) / sizeof(arr[0] ); i++) << WRONG!
Don't use sizeof(arr), better to use strlen(arr) - 1 instead of. 不要使用sizeof(arr),最好使用strlen(arr)-1。 BTW you can split your array with strtod function.
顺便说一句,您可以使用strtod函数拆分数组。 When you programming in C-style it would be more effective if you'll use functions from C lybrary( strlen, strtod, etc.)
当您使用C风格进行编程时,如果使用C lybrary中的函数(strlen,strtod等),效果会更好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.