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
#include <iostream>
#include <string>
#include <set>
usingnamespace std;
// write this function to help you out with the computation.
unsignedlong 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;
}
unsignedlong countWords(const string& s, set<string>& wl){
unsignedlong 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;
}