首页 > 解决方案 > 为什么我的解析字符串代码有额外的空间?

问题描述

我的作业代码有问题。一切都正确输出,除了我在“第一次”输出后获得了额外的空间。我的代码如下所示,请帮助我修复额外的空间。

#include <iostream>
#include <string>
#include <sstream>
using namespace std;

int main() {

    string userStr; 
    bool inputDone = false; 
    while(!inputDone)
    {
        bool commaCheck = false;    
        do
        {   
            
            cout << "Enter input string:" << endl;
            getline(cin, userStr);
            if (userStr == "q")     
            {
                inputDone = true;
                break;
            }
            else{
                
            for (unsigned int i = 0; i < userStr.length(); i++)
            {
                if (userStr[i] == ',')  
                    commaCheck = true;
            }
            if (!commaCheck)    
            {
                cout << "Error: No comma in string." << endl << endl;
            }
        }
        } while (!commaCheck);
    if(!inputDone)
    {
        string first, second;
        istringstream stream(userStr);
        getline(stream, first, ',');
        stream >> second;

        cout << "First word: " << first << endl;
        cout << "Second word: " << second << endl;
        cout << endl;
    }
    }
    return 0;
}

标签: c++

解决方案


如果您使用std::getline(stream, first, ',');并且您的单词和逗号之间有空格,那么它当然会在first中。因为你告诉std::getline我:在你看到逗号之前把所有东西都给我。

如果有人输入“a,b”,那么你首先有前导和尾随空格。

您需要“修剪”您的字符串,这意味着删除前导和尾随空格。

在 SO 上发布了许多修剪功能。请在此处查看示例

如果您发现其他问题,请告知


推荐阅读