简体   繁体   中英

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. 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;
}

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!

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.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM