Was just trying to do a simple challenge problem and can't figure out why this doesn't work?? Splitting a string into a vector based on ascii value to separate words, so I can later call the length to find the longest word in the string. I am getting out of bounds on the second word when I try to display from vector, but I don't think it should be unless I am forgetting something? First word displays as it should. I feel like this is probably painfully obvious but I've looked at it for awhile.
#include <iostream>
#include <string>
#include <vector>
#include <cctype>
usingnamespace std;
vector<string> SplitWords(const string& str) {
vector<string> words;
string w;
// looping one-past-the-end to process a word that ends at size()-1
for (size_t i = 0; i <= str.size(); ++i) {
if (i < str.size() && isalpha(str[i]))
w += str[i];
elseif (!w.empty()) {
words.push_back(w);
w.clear();
}
}
return words;
}
int main() {
auto split = SplitWords("test#$ length");
for (constauto& s: split)
cout << s << '\n';
}