I got a Segmentation fault in the following program.
Why is this happening and how can I fix it?
#include <string>
#include <vector>
#include <iostream>
#include <algorithm>
std::vector<std::string> split_words(std::string s) {
std::vector<std::string> v(1, "");
int i=0;
int wortanzahl = 0;
while(i<s.size()) {
if (s[i]!=' ') {
v.resize(wortanzahl + 1, "");
for (int j=i; s[j]!=' '; ++j) {
v[wortanzahl] += s[j];
i=j;
}
++wortanzahl;
}
++i;
}
}
int main() {
std::string s = "Alpha beta! Gamma";
split_words(s);
return 0;
}
std::istringstreamto split the words on a space. You don't need to write these types of loops to do this job.jrunning off the end ...