【问题标题】:How to take a line as an input and not include spaces如何将一行作为输入而不包含空格
【发布时间】:2015-09-13 21:38:38
【问题描述】:

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

#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;

}

【问题讨论】:

    标签: c++ string input stack getline


    【解决方案1】:

    您可以针对" \t\r" 显式测试每个字符,或者您可以使用cctypes 中声明的isspace 函数:

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

    我已经更新了my answer to your other question

    【讨论】:

      【解决方案2】:

      在 C 中,字符串本质上是一堆字符指针。您可以参考this SO post 了解如何通过移动指针从输入字符串中删除空格的一些示例。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-04-10
        • 2020-06-17
        • 2012-07-14
        • 2023-03-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多