Home >Backend Development >C++ >How to Parse a Comma-Delimited String into an Integer Array Using std::stringstream?

How to Parse a Comma-Delimited String into an Integer Array Using std::stringstream?

DDD
DDDOriginal
2024-12-19 17:10:13987browse

How to Parse a Comma-Delimited String into an Integer Array Using std::stringstream?

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:

  1. Instantiate a Stringstream Object:

    std::stringstream ss(str);

    This creates a stringstream object ss that reads from the comma-separated string str.

  2. 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.

  3. 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().

  4. Store the Numbers in an Array:

    vect.push_back(i);

    Add each extracted number i to a vector or array, such as vect.

  5. 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn