How to use stringstream to separate comma separated strings

C++TokenizeStringstream

C++ Problem Overview


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

C++ Solutions


Solution 1 - C++

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

> abc
def
ghi

Solution 2 - C++

#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
    std::string input = "abc,def,   ghi";
    std::istringstream ss(input);
    std::string token;
    size_t pos=-1;
    while(ss>>token) {
      while ((pos=token.rfind(',')) != std::string::npos) {
        token.erase(pos, 1);
      }
      std::cout << token << '\n';
    }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionB FaleyView Question on Stackoverflow
Solution 1 - C++jrokView Answer on Stackoverflow
Solution 2 - C++KishView Answer on Stackoverflow