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
-
8Splitting a string in C++ contains everything a human should know about splittin strings in C++pmr– pmr2012年07月30日 10:27:49 +00:00Commented Jul 30, 2012 at 10:27
-
Second answer in the duplicate target also answers this question: stackoverflow.com/a/236803/2527795VLL– VLL2018年10月31日 12:15:04 +00:00Commented Oct 31, 2018 at 12:15
2 Answers 2
#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
Dmitry Gusarov
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
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.
akmin04
In Kotlin, you can declare functions inside
companion object
inside classes which are basically static methods.Jay
This is short and readable which is great, but is this the fastest way to do it in c++?
|
#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';
}
}
1 Comment
Ashok Arora
This code isn't correct, it generates
abcdef \n ghi
as output.lang-cpp