Home >Backend Development >C++ >How Can I Split a Comma-Separated String in C Using Stringstream?
Separate Comma-Separated Strings Using Stringstream
This article addresses the issue of separating strings that are delimited by commas using a stringstream. The original code provided by the user attempted to use the operator to split the string, but it only worked for spaces, not commas.
To overcome this limitation, the solution employs the istringstream class and the getline function. Here's the revised code:
#include <iostream> #include <sstream> int main() { std::string input = "abc,def,ghi"; std::istringstream ss(input); std::string token; while (std::getline(ss, token, ',')) { std::cout << token << '\n'; } return 0; }
In this code, the getline function is used to extract each token from the stringstream. It takes three arguments: the input stream, the token, and the delimiter (in this case, a comma). The token is then printed to the console.
When you execute this code, it will produce the following output:
abc def ghi
This revised code successfully separates the string based on commas and provides the desired output.
The above is the detailed content of How Can I Split a Comma-Separated String in C Using Stringstream?. For more information, please follow other related articles on the PHP Chinese website!