How to use stringstream to separate comma separated strings [duplicate]
Asked Answered
U

2

176

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

Undercroft answered 30/7, 2012 at 10:21 Comment(2)
Splitting a string in C++ contains everything a human should know about splittin strings in C++Executive
Second answer in the duplicate target also answers this question: https://mcmap.net/q/40394/-how-do-i-iterate-over-the-words-of-a-stringBismuth
T
340
#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

Trematode answered 30/7, 2012 at 10:26 Comment(6)
Why do you guys always use std:: and full namespaces instead of using namespace? Is there specific reasoning for this? I just always find it as a very noisy and had-to-read syntax.Idiocy
@DmitryGusarov It's a habit and a good practice. It doesn't matter in short examples, but using namespace std; is bad in real code. More here.Trematode
ah, so it sounds like the problem caused by c++ ability to have a method outside of a class. And probably this is why it never lead to problem in C# / Java. But is it a good practice to have a method outside of a class? Modern languages like Kotlin don't even allow static methods.Idiocy
In Kotlin, you can declare functions inside companion object inside classes which are basically static methods.Misfeasance
This is short and readable which is great, but is this the fastest way to do it in c++?Aviv
How do you adapt this answer to skipping white spaces e.g., if std::string input = "abc, def, ghi"; I want to get rid of the white spaces when parsing by commas with getline.Convolve
U
5
#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';
    }
}
Upperclassman answered 22/3, 2017 at 8:19 Comment(1)
This code isn't correct, it generates abcdef \n ghi as output.Radial

© 2022 - 2024 — McMap. All rights reserved.