I have a program that requires to reverse the name which is a string, here's the code...
it's suppose to work, no errors found.... but "Run time error"

int i = fullName.length();	
while (i>=0)
{
   cout<<"Your reversed full Name is: ";
   cout<<fullName.substr(i-1, 1);
   i--;
}

thanks

If you insist on doing it this way then try the string's [] operator.

int i = fullName.length();
cout<<"Your reversed full Name is: ";	
while (i>=0)
{
   cout<<fullName[i];
   i--;
}

Please note that the string object has iterators which would handle this problem nicely.

Edited 6 Years Ago by gerard4143: n/a

when i is equal to zero you are doing i-1 which i'm assuming is causing the error because fullname[-1] is out of range

when i is equal to zero you are doing i-1 which i'm assuming is causing the error because fullname[-1] is out of range

I don't think it is a case here because the -1 will drop out of the loop. Though, the issue is where 'i' is being use as 1-index, not 0-index. The correct value for initiating 'i' should be fullName.length()-1;

OK, sorry. Your post is right under gerard, so I would assume that you are commenting his code, not the OP code.

May I suggest std::reverse ?

#include <string>
#include <iostream>
#include <algorithm>

[...]

std::string name = "your name";
std::reverse(name.begin(), name.end());
std::cout << "reversed: " << name;

If you insist on doing it this way then try the string's [] operator.

int i = fullName.length();
cout<<"Your reversed full Name is: ";	
while (i>=0)
{
   cout<<fullName[i];
   i--;
}

Please note that the string object has iterators which would handle this problem nicely.

Thanks,
it work very well!

May I suggest std::reverse ?

#include <string>
#include <iostream>
#include <algorithm>

[...]

std::string name = "your name";
std::reverse(name.begin(), name.end());
std::cout << "reversed: " << name;

I just tried this, and it also work just fine!
Thanks!

This article has been dead for over six months. Start a new discussion instead.