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.

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;

i don't mean i = -1, but his substring line:

cout<<fullName.substr(i-1, 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!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.