Parse string containing numbers into integer array

arrays, c++, parsing, string

Solution

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

Problem

A String is given as an input which consists of numbers and I want to convert it into integer arrays in C++. ``` #include <string> #include <iostream> #include <sstream> using std::string; using std::stringstream; using std::cout; using std::endl; int main(int argc,char** argv) { string num="-24 2 90 24 50 76"; stringstream stream(num); while(stream){ int n; stream>>n; cout<<n<<endl; } return 0; } ``` Output(GCC) : -24 2 90 24 50 76 76 Why am i getting extra value and what is the efficient to convert them into integer array ? UPDATE: What if the string stream contains delimiter other than space, How to parse this? For eg: `string num="-24,2,90,24,50,76";`

Original source