拆分c ++字符串提升?

时间:2014-01-04 02:48:08

标签: c++ string boost split

给出一个字符串,例如" 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 ?

迭代后,我只获得名字而不是完整的详细信息

2 个答案:

答案 0 :(得分:8)

更新:由于您正在阅读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

虽然您可能想要删除空格。

答案 1 :(得分:8)

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

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