170

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

Community
  • 1
  • 1
B Faley
  • 17,120
  • 43
  • 133
  • 223
  • 8
    [Splitting a string in C++](http://stackoverflow.com/questions/236129/splitting-a-string-in-c) contains everything a human should know about splittin strings in C++ – pmr Jul 30 '12 at 10:27
  • Second answer in the duplicate target also answers this question: https://stackoverflow.com/a/236803/2527795 – VLL Oct 31 '18 at 12:15

2 Answers2

333
#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

Yola
  • 18,496
  • 11
  • 65
  • 106
jrok
  • 54,456
  • 9
  • 109
  • 141
  • 1
    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. – Dmitry Gusarov Oct 14 '19 at 02:45
  • 28
    @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](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice). – jrok Oct 14 '19 at 07:37
  • 1
    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. – Dmitry Gusarov Oct 16 '19 at 02:00
  • In Kotlin, you can declare functions inside `companion object` inside classes which are basically static methods. – akmin04 Oct 21 '19 at 00:44
  • This is short and readable which is great, but is this the fastest way to do it in c++? – Jay Apr 07 '20 at 14:43
  • 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. – 24n8 Aug 16 '21 at 21:40
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';
    }
}
Kish
  • 59
  • 1
  • 3