jeudi 29 janvier 2015

How to copy a list of numbers from a string to a C++ vector

I have a string like:



string line="6,148,72,35,0,33.6,0.627,50,1";


and I would like to copy the numbers within it to the respective elements of a std::vector. I would like to use std::vector.assign() or std::copy().


So I wrote:



string line="6,148,72,35,0,33.6,0.627,50,1";
vector<double> row;
istringstream iss { line };
row.assign(istream_iterator<double>(iss), istream_iterator<double>());


but the result is that assign() only copies the first number from the string to the vector, i.e. I get



row={6}


while I would like to get



row={6,148,72,35,0,33.6,0.627,50,1}


Same thing if I use std::copy instead, like in:



string line="6,148,72,35,0,33.6,0.627,50,1";
vector<double> row;
istringstream iss { line };
copy(istream_iterator<double>(iss), istream_iterator<double>(), back_inserter(row));


It looks like copy from the string ends after reading the first number, and I don't know why. Any idea how to use assign() or copy() to copy every number from the string into the vector?


Aucun commentaire:

Enregistrer un commentaire