Parsing a Comma-Delimited String Using std::stringstream
To parse a comma-separated string into an integer array, you can leverage the power of std::stringstream. Here's a step-by-step guide on how to achieve this:
Instantiate a Stringstream Object:
std::stringstream ss(str);
This creates a stringstream object ss that reads from the comma-separated string str.
Iterate Through the Stream:
for (int i; ss >> i;) { // ... }
Use a for loop to extract numbers from the stringstream. Each iteration attempts to read an integer i from ss. If successful, the following character in the stream must be a comma.
Check for Commas:
if (ss.peek() == ',') ss.ignore();
After extracting each number i, check if the next character in the stream is a comma. If so, discard it using ignore().
Store the Numbers in an Array:
vect.push_back(i);
Add each extracted number i to a vector or array, such as vect.
Iterate and Display Results:
for (std::size_t i = 0; i < vect.size(); i++) std::cout << vect[i] << std::endl;
Finally, iterate through the vector or array to display or use the parsed numbers as needed.
The above is the detailed content of How to Parse a Comma-Delimited String into an Integer Array Using std::stringstream?. For more information, please follow other related articles on the PHP Chinese website!