Problem with string.length()

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.
Last edited on
Check k and n-k to be valid on line 12
http://www.cplusplus.com/reference/string/string/substr/
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.
What does the error say?
Im using visual studio 2005
when i run it, the window pops up ands and says

Debug Error!

Program: ...
This application has requested the runtime to terminate in an unusual way. please contact admin...etc.
bounds check problem.

1
2
3
int k = text.length(); //  "Hello World" has length 11, valid indices 0-10.

isalpha( text[ k ] );  // accesses index 11. 
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.
thanks, i solved the problem now with that.

I ended up replacing my k's in the while statement with k-1 to address the problem. thanks alot!
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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <string>
#include <iostream>

int main() {
    std::string helloWorld = "Hello World!\n";

    // Demonstrate forward iterators
    for( std::string::const_iterator ch = helloWorld.begin(); ch != helloWorld.end(); ++ch )
       std::cout << *ch;

    // Demonstrate reverse iterators
    for( std::string::const_reverse_iterator ch = helloWorld.rbegin(); ch != helloWorld.rend(); ++ch )
       std::cout << *ch;
}

Topic archived. No new replies allowed.