Suppose I have a string of numbers
"1 2 3 4 5 6"
I want to split this string and place every number into a different slot in my vector. What is the best way to go about this
Use istringstream to refer the string as a stream and >>
operator to take the numbers. It will work also if the string contains newlines and tabs. Here is an example:
#include <vector>
#include <sstream> // for istringstream
#include <iostream> // for cout
using namespace std; // I like using vector instead of std::vector
int main()
{
char *s = "1 2 3 4 5";
istringstream s2(s);
vector<int> v;
int tmp;
while (s2 >> tmp) {
v.push_back(tmp);
}
// print the vector
for (vector<int>::iterator it = v.begin(); it != v.end(); it++) {
cout << *it << endl;
}
}
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