Exploiting getline() for Comma-Separated String Separation
To separate comma-separated strings in C , stringstream alone may not suffice. This article presents an alternative approach using the getline() method to achieve the desired separation.
In the given code, the stringstream::>> operator separates strings based on whitespace. To handle commas, you can incorporate getline() from the
Consider the following modified version of the 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, we use getline() to extract tokens from the stringstream by specifying a comma as the delimiter. The output is:
abc def ghi
By harnessing the capabilities of getline(), you can effectively separate strings by any specific delimiter, including commas. This approach offers greater flexibility and customization for string manipulation tasks.
The above is the detailed content of How Can `getline()` Be Used to Separate Comma-Separated Strings in C ?. For more information, please follow other related articles on the PHP Chinese website!