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.
From a purely philosophical point of view: yes, a string is a type of vector. It is a contiguous memory block that stores characters (a vector is a contiguous memory block that stores objects of arbitrary types). So, from this perspective, a string is a special kind of vector.
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 );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With