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

陌路散爱 提交于 2019-12-13 06:55:53

问题


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;

}

回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/31081551/how-to-take-a-line-as-an-input-and-not-include-spaces

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!