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
Release: 2024-12-19 17:10:13
Original
913 people have browsed it

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);
    Copy after login

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

  2. Iterate Through the Stream:

    for (int i; ss >> i;) {
        // ...
    }
    Copy after login

    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();
    Copy after login

    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);
    Copy after login

    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;
    Copy after login

    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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template