I'm trying to write code that initializes a string into a vector by splitting it at every space character. Somehow the temporary vector won't take the positions and it doesn't split the string right.
#include <iostream>
#include <string>
#include <vector>
std::vector<std::string> splitStr(std::string s, char cut = 32) {
std::string temp = s;
int begin = 0;
std::vector<std::string> v;
for (int i = 0; i < temp.length() - 1; ++i) {
if ((int) cut == (int) temp[i]) {
v.push_back(temp.substr(begin, i));
begin = i + 1;
}
}
return v;
}
using namespace std;
int main() {
for (string e : splitStr("Hello this is a test!", ' ')) {
cout << e << endl;
}
}
I think it goes wrong while appending to the vector, but I don't get why that is. Can any of you guys tell me what I'm doing wrong?