Stringstream to vector<int>

Jean-Luc picture Jean-Luc · Feb 4, 2012 · Viewed 11k times · Source

I'm wondering what the best way to write from an std::stringstream into a vector<int>.

Here's an example of what's in the stringstream: "31 #00 532 53 803 33 534 23 37"

Here's what I've got:

int buffer = 0;
vector<int> analogueReadings;
stringstream output;

 while(output >> buffer)
     analogueReadings.push_back(buffer);

However what seems to happen is, it reads the first thing, then it gets to #00 and returns 0 because it's not a number.

Ideally, what I want is, it gets to a # and then just skips all characters until the next whitespace. Is this possible with flags or something?

Thanks.

Answer

Andr&#233; Caron picture André Caron · Feb 4, 2012
#include <iostream>
#include <sstream>
#include <vector>

int main ( int, char ** )
{
    std::istringstream reader("31 #00 532 53 803 33 534 23 37");
    std::vector<int> numbers;
    do
    {
        // read as many numbers as possible.
        for (int number; reader >> number;) {
            numbers.push_back(number);
        }
        // consume and discard token from stream.
        if (reader.fail())
        {
            reader.clear();
            std::string token;
            reader >> token;
        }
    }
    while (!reader.eof());

    for (std::size_t i=0; i < numbers.size(); ++i) {
        std::cout << numbers[i] << std::endl;
    }
}