178

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

asked Jul 30, 2012 at 10:21
2
  • 8
    Splitting a string in C++ contains everything a human should know about splittin strings in C++ Commented Jul 30, 2012 at 10:27
  • Second answer in the duplicate target also answers this question: stackoverflow.com/a/236803/2527795 Commented Oct 31, 2018 at 12:15

2 Answers 2

343
#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
19.3k12 gold badges68 silver badges119 bronze badges
answered Jul 30, 2012 at 10:26
Sign up to request clarification or add additional context in comments.

6 Comments

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.
@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.
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.
In Kotlin, you can declare functions inside companion object inside classes which are basically static methods.
This is short and readable which is great, but is this the fastest way to do it in c++?
|
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';
 }
}
answered Mar 22, 2017 at 8:19

1 Comment

This code isn't correct, it generates abcdef \n ghi as output.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.