mskoryk
mskoryk

Reputation: 506

parse string to vector of int

I have a string which contains some number of integers which are delimited with spaces. For example

string myString = "10 15 20 23";

I want to convert it to a vector of integers. So in the example the vector should be equal

vector<int> myNumbers = {10, 15, 20, 23};

How can I do it? Sorry for stupid question.

Upvotes: 26

Views: 36716

Answers (3)

Vlad from Moscow
Vlad from Moscow

Reputation: 310980

std::string myString = "10 15 20 23";
std::istringstream is( myString );
std::vector<int> myNumbers( ( std::istream_iterator<int>( is ) ), ( std::istream_iterator<int>() ) );

Or instead of the last line if the vector was already defined then

myNumbers.assign( std::istream_iterator<int>( is ), std::istream_iterator<int>() );

Upvotes: 13

user1508519
user1508519

Reputation:

This is pretty much a duplicate of the other answer now.

#include <iostream>
#include <vector>
#include <iterator>
#include <sstream>

int main(int argc, char* argv[]) {
    std::string s = "1 2 3 4 5";
    std::istringstream iss(s);
    std::vector<int> v{std::istream_iterator<int>(iss),
                       std::istream_iterator<int>()};
    std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, " "));
}

Upvotes: 0

Abhishek Bansal
Abhishek Bansal

Reputation: 12715

You can use std::stringstream. You will need to #include <sstream> apart from other includes.

#include <sstream>
#include <vector>
#include <string>

std::string myString = "10 15 20 23";
std::stringstream iss( myString );

int number;
std::vector<int> myNumbers;
while ( iss >> number )
  myNumbers.push_back( number );

Upvotes: 38

Related Questions