I am trying to write a function in a program that takes a string and outputs the last word. However, whenever i call up the fuction, i get a runtime error on the console. The code that I have right now is
1 2 3 4 5 6 7 8 9 10 11 12 13 14
string getLastWord(string text)
{
int k=text.length();
int n;
cout<<text.size();
while (!isalpha(text[k]))
{k--;}
n = k;
while (isalpha (text[k]))
{k--;}
text.substr (k, (n-k));
return text;
}
I tried removing some things, and determined that the part where i define int k is what causes my runtime error, but i can't find a way to do it otherwise. So i was just wondering what's causing the runtime error in the code.
Sorry, what do you mean by checking if it's valid?
i tried replacing k with 5 and (n-k) with 3 on line 12, which i assumed would work since cout<<text.size() gave me a value of 17. However, i still get an unexpected runtime error.
You have a very basic problem accessing the array which leads to undefined behavior. text is a zero based array. k is initialized to lenth. If the length is 10, k = 10, and 10 is not a valid element of the string. The string elements are 0-9.
You could avoid the problem using string::begin and string::end. Then you can use reverse iterators to access the elements since string provides iterators.
But it is worth reiterating (pun intended, I think) that had you used iterators, you could have avoided the problem in the first place. Iterators virtually eliminate the one-off problems. Since this program is so short, you should spend
some time to learn about iterators and then rewrite your program to use them.