【问题标题】:Split c++ string boost?拆分C++字符串提升?
【发布时间】:2014-01-04 02:48:07
【问题描述】:

给定一个字符串,例如“John Doe , USA , Male”,我将如何用逗号作为分隔符分割字符串。目前我使用 boost 库,我设法拆分,但空白会导致问题。

例如,上面的字符串一旦被分割成一个向量,就只包含“John”而不包含其余部分。

更新

这是我目前正在使用的代码

    displayMsg(line);   
    displayMsg(std::string("Enter your  details like so David Smith , USA, Male OR q to cancel"));
    displayMsg(line);

    std::cin >> res;    
    std::vector<std::string> details;
    boost::split(details, res , boost::is_any_of(","));

// If I iterate through the vector there is only one element "John" and not all ?

迭代后我只得到名字而不是完整的细节

【问题讨论】:

  • details.size() 的值是多少?拨打boost::split之后?
  • 我已经更新了这个问题。我也得到大小为 1

标签: c++ string boost split


【解决方案1】:

实际上,您可以在没有提升的情况下做到这一点。

#include <sstream>
#include <string>
#include <vector>
#include <iostream>

int main()
{
    std::string res = "John Doe, USA, Male";
    std::stringstream sStream(res);
    std::vector<std::string> details;
    std::string element;
    while (std::getline(sStream, element, ','))
    {
        details.push_back(element);
    }

    for(std::vector<std::string>::iterator it = details.begin(); it != details.end(); ++it)
    {
        std::cout<<*it<<std::endl;
    }
}

【讨论】:

    【解决方案2】:

    更新:由于您是从 cin 读取的,因此当您输入空格时,它自然会停止读取。它被读作一个停止。由于您正在读取字符串,因此处理此问题的更好方法是使用 std::getline

    #include <boost/algorithm/string/split.hpp>
    #include <boost/algorithm/string.hpp>
    #include <iostream>
    #include <vector>
    
    using namespace std;
    using namespace boost;
    
    int main(int argc, char**argv) {
        std::string res;
        std::getline(cin, res);
        std::vector<std::string> details;
        boost::split(details, res, boost::is_any_of(","));
        // If I iterate through the vector there is only one element "John" and not all ?
        for (std::vector<std::string>::iterator pos = details.begin(); pos != details.end(); ++pos) {
            cout << *pos << endl;
        }
    
        return 0;
    }
    

    输出如下:

    John Doe
    John Doe
     USA
     Male
    

    虽然您可能想去掉空格。

    【讨论】:

    • 但是如果数据是通过标准输入进来的,那么它就不起作用了。使用 cin 从输入中读取字符串。我已经更新了这个问题,因为这就是我想要做的。然后当我打印出向量的内容时,我只得到 John
    猜你喜欢
    • 2020-10-10
    • 1970-01-01
    • 2013-01-15
    • 2017-06-16
    • 2011-02-13
    • 2011-11-25
    • 2021-05-08
    相关资源
    最近更新 更多