Firstly, it would be better on line 5 if you used "getline" rather than "cin" because "cin" only gets characters up to a space rather than the entire thing and can leave characters in the input buffer. Like this:
getline(cin, thefilename);
There is also another error at line 9 which is the fact that the console outputs text but then it closes down simply because you have not told it to pause. A simple "cin.ignore();" can solve that issue.
As for the loop between lines 13 and 22, there is no need to use a for loop inside a while loop. The code should look something like this:
1 2 3 4 5 6 7 8 9 10 11 12 13
vector<string> str;
while (!file.eof())
{
string temp;
getline(file, temp);
str.push_back(temp);
}
file.close();
int lastwordpos = str[str.size() - 1].find_last_of(" ");
string lastword = str[str.size() - 1].substr(lastwordpos, (str.size() - lastwordpos));
cout << "The last word is " << lastword << endl;
cin.get();
return 0;
You'll need to include this preprocessor directive at the top of your source otherwise you won' be able to use a vector.
#include <vector>
Your code should now work if you replace your part of the code with this part.
file.close();
int lastwordpos = str[str.size() - 1].find_last_of(" ");
string lastwordis = str[str.size() - 1].substr(lastwordpos, (str.size() - lastwordpos));
cout << "The last word is " << lastwordis << endl;
// for (int i = 0; i < lastwordis.length(); i++)
// {
// lastwordis = lastwordis.substr(0,lastwordis.length()-1);
// }
cout << lastwordis << endl;
cin.get();
return 0;
}
when i run this code with text file i get this output: libc++abi.dylib: terminating with uncaught exception of type std::out_of_range: basic_string
(lldb)
Sorry! That was my fault why the code didn't work. I didn't test it beforehand so there was bound to be an error in it. I've no solved the problem and this is the new code: