Parse string containing numbers into integer array

The end of file condition is not set upon a succesful parse, you have to check the state of the stream after parsing.

The second 76 is basically just pure chance. An unsuccesful parse leaves the target operand untouched, and because you did not initialize n, it can be anything.

A quickfix:

stream>>n;
if (stream)
    cout<<n<<endl;

A cleaner fix:

int n;
while(stream >> n){
    cout<<n<<endl;
}

To store those integers, the canonical way is to use std::vector if the number of elements is unknown. An example usage:

std::vector<int> values;
int n;
while(stream >> n){
    ...do something with n...
    values.push_back(n);
}

However, you can use iterators over streams and use the following:

// Use std::vector's range constructor
std::vector<int> values(
     (std::istream_iterator<int>(stream)), // begin
     (std::istream_iterator<int>()));      // end

Leave a Comment