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';
}
}
Related videos on Youtube
Author by
B Faley
Updated on February 02, 2020Comments
-
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,ghiSo 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-
pmr almost 12 yearsSplitting a string in C++ contains everything a human should know about splittin strings in C++
-
VLL over 5 yearsSecond answer in the duplicate target also answers this question: stackoverflow.com/a/236803/2527795
-
-
Dmitry Gusarov over 4 yearsWhy 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 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 over 4 yearsah, 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 over 4 yearsIn Kotlin, you can declare functions inside
companion object
inside classes which are basically static methods. -
Jay about 4 yearsThis is short and readable which is great, but is this the fastest way to do it in c++?
-
Ashok Arora over 3 yearsThis code isn't correct, it generates
abcdef \n ghi
as output. -
24n8 almost 3 yearsHow 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.