s2k s2k - 3 months ago 50
C++ Question

How to use stringstream to separate comma separated strings

I've got the following code:

std::string str = "abc def,ghi";
std::stringstream ss(str);

string token;

while (ss >> token)
{
printf("%s\n", token.c_str());
}


The output is:


abc

def,ghi


So the
stringstream::>>
operator can separate strings by space but not by comma. Is there anyway to modify the above code so that I can get the following result?


input: "abc,def,ghi"

output:

abc

def

ghi

Answer
#include <iostream>
#include <sstream>

std::string input = "abc,def,ghi";
std::istringstream ss(input);
std::string token;

while(std::getline(ss, token, ',')) {
    std::cout << token << '\n';
}