user855
user855

Reputation: 19918

Can I pass a string to istream_iterator<int>

I have a string object that contains the value "1 2 3"

Can I use the istream_iterator to extract the values 1, 2 and 3

Upvotes: 1

Views: 289

Answers (2)

wilhelmtell
wilhelmtell

Reputation: 58667

Use a std::istringstream:

#include<sstream>
#include<iterator>

// ...
std::string s("1 2 3");
std::istringstream ss(s);
std::copy(std::istream_iterator<int>(ss), std::istream_iterator<int>(),
          std::ostream_iterator<int>(std::cout, "-"));

Upvotes: 0

Benjamin Lindley
Benjamin Lindley

Reputation: 103693

You can, like this:

std::string str = "1 2 3";
std::vector<int> v;
std::istringstream iss(str);
std::istream_iterator<int> begin(iss), end;
std::copy(begin,end,back_inserter(v));

Upvotes: 2

Related Questions