std::out_of_range

Jun 17, 2012 at 9:29am
Hello all,

Sorry to bother you all with a seriously newbie error but I can't for the life of me work out what I'm doing wrong here. Just learning to code and my housemate gave me a project - take a phrase and output it in reverse.

I get an out of range error each time.
The first part of the code just gets input from the user with getline and that seems to work fine. It seems to give me the error during the loop of rEngine.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
string rEngine (string str)
{
	string r;
	string z;
	int x;						
	x = str.length();			
	z.resize (x);				
	r.resize (x);				
	while (x >= 0)
	{
	z.assign(0,1,str.at(x));	
	r.append(z);				
	--x;
	}

	return (r);
}
Jun 17, 2012 at 9:43am
The problem is str.at(x) when x == str.length().
Jun 17, 2012 at 10:04am
how is it a problem? if the value of (x) is equal to the length of the parsed string, the first loop should simply take the last character of the string (str) and assign it to the string (z).

I left the loop out of the code to test if I could display the length of a string (str.length()) after passing that value to an integer - so,

x = str.length()

cout << x;

and I got an out of range error again ?
Jun 17, 2012 at 10:13am
Remember that indices starts at zero so str.at(str.length()) is one character past the end.
Jun 17, 2012 at 1:45pm
Hmm, I changed the code to read x = str.length() - 1; and it still goes out of range. Confusing... do I need to specify the integer as long or some other type...
Jun 17, 2012 at 3:29pm
Wow... so it turns out Eclipse was compiling the new project but, for some reason, launching an old .exe. This gave me the impression that I kept going out of bounds, when really Eclipse was building the right project but launching a completely different one (the same project with a different name, compiled hours ago).

Bloody hell. Fixed now,
1
2
3
4
5
6
7
8
9
10
11
12
string rEngine (string str)
{
	string r;
	int x;
	x = str.length()-1;

	while (x >= 0)
	{
		x == str.length() ? --x : (r.push_back(str.at(x)), --x);
	}
	return (r);
}

Works just fine. Thankyou Peter87 for your advice, the -1 is important.

Solved.
Topic archived. No new replies allowed.