HELP! I need help understanding this error message

My code is supposed to take in a string and return how many words are in the line. The code compiles, however I am receiving an error message that I do not understand. I have a feeling that the message pertains to how I am inputing my text. My code is displayed below so if anyone can help me I would greatly appreciate it. Thank You very much.


Error Message : libc++abi.dylib: terminating with uncaught exception of type std::out_of_range: basic_string
Abort trap: 6

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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include <iostream>
#include <string>
#include <set>
using namespace std;


// write this function to help you out with the computation.
unsigned long countWords(const string& s, set<string>& wl);


int main()
{
        char response;
        string str;
        int words;
        set<string>lines;

        //assurance the code will run because 1 is always true
        while(1){

                //user input to run the program; if n loop will break
                cout << "Would you like to run the program? Enter Y or N\n";
                cin >> response;
                if(response == 'n'||response == 'N') break;
                cin.ignore();


                cout << "Enter a string\n";
                getline(cin, str);
                lines.insert(str);

                int words = countWords(str, lines);
                cout << "The amount of words in your string is "<<words<<endl;
                }
        return 0;
}


unsigned long countWords(const string& s, set<string>& wl){

        unsigned long count = 0;//count words
        int countchar = 0;//count char
        for(int i = 0; i <= s.length(); i++){
                if(s.at(i)==' ' || s.at(i+1) == '\0' ){
                        //inserts a substring
                        wl.insert(s.substr(i-countchar-1, countchar));
                        count++;
                        countchar++;
                }
                else countchar++;


        }
        return count;
}



Last edited on
Problem is line 43:
i <= s.length()

After you fix that, the next error you get will be on next line:
s.at(i+1)

Note easier way to do this is to make use of istringstream and the >> operator:
http://www.cplusplus.com/reference/sstream/istringstream/istringstream/
Topic archived. No new replies allowed.