How to take a line as an input and not include spa

2019-09-06 03:25发布

I'm working on a project to convert from postfix to infix expressions. I was stuck for a while but I had part of it working then I realized I needed to inlcude a space between each of the operands when I input it to the user.I'm not sure how to take in a string and not include spaces how would I go about doing that. getline doesn't work as it includes spaces. therefore instead of ab+ I need to accept it as: a b +. i'm not sure how to do this not include the strings. Here is my code so far.

#include "stack.h"

void convert(string expression){

    stack c;

    string post =" ";
    string rightop="";
    string leftop="";
    string op ="";

    for (int i =0; i<=expression.length()-1;i++){
        c.push(expression[i]);
        c.print();

        if (expression[i] == '*' ||
            expression[i] == '+' ||
            expression[i] == '-' ||
            expression[i] == '/'){
            cout<<c.top()<<endl;
            leftop=c.top();
            cout<<leftop<<endl;

            c.pop();


            rightop=c.top();
            cout<<rightop<<endl;
            c.pop();
            op=c.top();
            cout<<op<<endl;
            c.top()=expression[i+1];
            //c.pop();
            post="(" + leftop + " " + op + " " + rightop + ")";

            cout<<post<<endl;
        }


        //c.push(post);
    }
}







int main(){

    string expression;
    cout<<" Enter a Post Fix expression: ";


    getline(cin,expression);

    convert(expression);

    return 0;

}

2条回答
We Are One
2楼-- · 2019-09-06 04:05

In C, strings are essentially a bunch of character pointers. You can refer to this SO post for a few examples of how to remove white space from your input string by moving pointers.

查看更多
神经病院院长
3楼-- · 2019-09-06 04:06

You can test explicitely each character against " \t\r", or you can use the isspace function declared in cctypes :

for (int i =0; i<=expression.length()-1;i++){
    if (isspace(expression[i])) continue;
    // remaining unchanged ...

I've update my answer to your other question with that.

查看更多
登录 后发表回答