I have the following string:
1 -2 -8 4 51
I would like to get a vector with 5 elements, each of them corresponding to the 5 numbers in the string. Basically, I'd like to split the above string by space as a delimiter.
I've found a lot of questions like this on Stack Overflow but so far any of them is able to get neither the first "1" nor the last one (from 51
).
My code is the following:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <sstream>
using namespace std;
std::vector<std::string> split(std::string str)
{
std::string buf;
std::stringstream ss(str);
vector<std::string> tokens;
while (ss >> buf)
tokens.push_back(buf);
return tokens;
}
int main()
{
std::string temps = "1 -2 -8 4 51";
std::vector<std::string> x = split(temps);
for (int j = 0; j < x.size(); j++){
cout << x[j] << endl;
}
}
My output is the following:
-2
-8
4
5
As you can see, the first and the last 1 are skipped.
I'm very new to C++ (I've been maybe too much used to the built-in functions .split()
of other languages) but I can't see anything wrong on my above code.
Can anyone please help me understanding what I'm doing wrong?