Reputation: 313
What is an easy way to convert a string
"1 0 2 1 4 5 6 195"
to an int array (or a vector)? I am aware of the possible solutions but they all seem too complicated for my purposes (string is formatted as given in example). std::string or char[] are both ok.
Upvotes: 1
Views: 510
Reputation: 29724
#include <string>
#include <vector>
#include <sstream>
#include <iterator>
// get string
std::string input = "1 0 2 1 4 5 6 195";
// convert to a stream
std::stringstream in( input);
// convert to vector of ints
std::vector<int> ints;
std::copy( std::istream_iterator<int, char>(in),
std::istream_iterator<int, char>(), std::back_inserter( ints ) );
Upvotes: 4