0

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

5
Contributors
8
Replies
9
Views
7 Years
Discussion Span
Last Post by slavacrilov
0

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 by gerard4143: n/a

1

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

0

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;

0

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

0

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;
0

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!

0

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 topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.