简体   繁体   中英

Split c++ string boost?

Given a string such as "John Doe , USA , Male" how would I go about splitting the string with the comma as a delimiter. Currently I use the boost library and I manage to split but white spacing causes issues.

For instance the above string once split into a vector only contains "John" and not the rest.

UPDATE

Here is the code I am working with so far

    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 ?

After iteration I get only first name and not full details

Updated: Since you're reading from cin it will by nature stop reading when you enter a space. It's read as a stop. Since you're reading into a string a better way of dealing with this is to use 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;
}

The output is as follows:

John Doe
John Doe
 USA
 Male

Although you might want to strip the whitespace.

Actually, you can do this without boost.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM