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);
}
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,
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...
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.