Splitting words from string into vector

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <iostream>
#include <string>
#include <vector>
using namespace std;

string LongestWord(string sen) {

vector<string> findlong;
string temp;

//iterate through string
for(int i=0; i< sen.length(); ++i){
  //if index of string is between ascii 97 - 122 concat to temp string
  if(sen[i] >= 97 && sen[i] <= 122){
        temp += sen[i];
  }
  else{
    if(temp == ""){ //else if not and temp string is already empty continue
      continue;
    }
    else{ //if not empty push temp string to vector and set blank;
      findlong.push_back(temp);
      temp = "";
    }
  }
}

cout << findlong.at(0);
cout << findlong.at(1);

return "done";


}



int main(){
cout << LongestWord("test#$ length");
return 0;
}
Your loop ends before you process the last word (if the last word ends at the very end of the string).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
#include <string>
#include <vector>
#include <cctype>
using namespace 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];
        else if (!w.empty()) {
            words.push_back(w);
            w.clear();
        }
    }

    return words;
}

int main() {
    auto split = SplitWords("test#$ length");
    for (const auto& s: split)
        cout << s << '\n';
}
Last edited on
@dutch ohhh yes you are absolutely right. Thank you.
Topic archived. No new replies allowed.