Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 813
MrSSS16 Avatar asked Dec 03 '22 20:12

MrSSS16


1 Answers

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;
    }
}
like image 190
jfly Avatar answered Dec 06 '22 11:12

jfly