Tokenize stringstream
I need a stream of string lines according to a custom delimiter. The current code is only truncated according to a few standard delimiters. How can I define and cut a stringstream
string line according to a custom delimiter?
std::istringstream input;
input.str("1\n2\n3\n4\n5\n6\n7\n");
int sum = 0;
for (std::string line; std::getline(input, line); )
{
cout<<line;
}
+3
source to share
2 answers
If you have one delimiter that you want to use, and that is one character, you can simply pass it to the 3-parameter overload std::getline()
:
std::istringstream input;
input.str("1;2;3;4;5;6;7;");
int sum = 0;
for (std::string field; std::getline(input, field, ';'); )
{
std::cout<<field;
}
In other situations (multi-character delimiter, multiple delimiters), you might consider using the Boost.Tokenizer .
+3
source to share