How to use stringstream to separate comma separated strings

280,622

Solution 1

#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

#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';
    }
}
Share:
280,622

Related videos on Youtube

B Faley
Author by

B Faley

Updated on February 02, 2020

Comments

  • B Faley
    B Faley over 4 years

    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

  • Dmitry Gusarov
    Dmitry Gusarov over 4 years
    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.
  • jrok
    jrok over 4 years
    @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.
  • Dmitry Gusarov
    Dmitry Gusarov over 4 years
    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.
  • akmin
    akmin over 4 years
    In Kotlin, you can declare functions inside companion object inside classes which are basically static methods.
  • Jay
    Jay about 4 years
    This is short and readable which is great, but is this the fastest way to do it in c++?
  • Ashok Arora
    Ashok Arora over 3 years
    This code isn't correct, it generates abcdef \n ghi as output.
  • 24n8
    24n8 almost 3 years
    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.