Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse string containing numbers into integer array

Tags:

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";

like image 302
djadmin Avatar asked Jul 18 '13 13:07

djadmin


2 Answers

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
like image 127
Sebastian Mach Avatar answered Sep 26 '22 09:09

Sebastian Mach


Another means of dealing with a character separated integers list using a vector, which is even perhaps a little more simplistic is more like this:

string str = "50,2,25,38,9,16";
vector<int> ints;
stringstream ss(str);
int n;
char ch;

while(ss >> n) {
    if(ss >> ch)
        ints.push_back(n);
    else
        ints.push_back(n);
}

that way you can move past any character separations (if they exist) first and then default back to grabbing the integers and adding them to the list if they don't (AKA the end of the list)

like image 40
Thacious Avatar answered Sep 23 '22 09:09

Thacious