如何以一条线作为输入,不包括空格 [英] How to take a line as an input and not include spaces

查看:141
本文介绍了如何以一条线作为输入,不包括空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个项目,从后缀转换为中缀表达式。我被卡住了一段时间,但我有一部分工作,然后我意识到,当我输入到用户时,我需要在每个操作数之间插入一个空格。我不知道如何接受一个字符串,不包括空格我怎么会这样做。 getline不工作,因为它包括空格。因此,而不是ab +我需要接受它:a b +。我不知道如何做到这一点不包括字符串。这是我的代码到目前为止。

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;

}


推荐答案

显式地测试每个字符\t\r,或者可以使用 isspace code> cctypes :

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

我更新了我对你的其他问题的答案

这篇关于如何以一条线作为输入,不包括空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆