Search code examples
c++stdvectorstdstring

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.


Solution

  • 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 );