Reputation: 1
What I'm trying to do is reading from char array and separate char by number and operator. 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.
#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;
}
Upvotes: 0
Views: 138
Reputation: 1489
Don't use sizeof(arr), better to use strlen(arr) - 1 instead of. BTW you can split your array with strtod function. When you programming in C-style it would be more effective if you'll use functions from C lybrary( strlen, strtod, etc.)
Upvotes: 0
Reputation: 68033
Don't use sizeof()
on char*
.
Better yet, use std:string
.
char * arr;
for(unsigned int i = 0; i < sizeof(arr) / sizeof(arr[0] ); i++) << WRONG!
Upvotes: 2