Reverse the string in C++

  • A+
Category:Languages
#include <iostream> #include <cstdlib> using namespace std;  main()  { beginning:     string name;     cout << "Hey! Enter your name" << endl;     cin >> name;     int i = name.length() - 1;     do     {         cout << name[i];         i--;     } while (i > -1);     cout << " Your reverse name is " << name[i] << endl;     cout << name[i] << " Your reverse name is " << endl;     goto beginning; } 

Reverse the string in C++

  1. Why the "zsuidakrA" is being displayed before "Your reverse name is" although I have coded like cout<<" Your reverse name is "<<name[i]<<endl;
  2. For cout<<name[i]<<" Your reverse name is "<<endl; this line, I have found only "Your reverse name is" but there is no name. Why?

 


You are first displaying the reverse string, then outputting Your reverse name is. But the string is never reversed. Use:

string reverse_name(name.rbegin(), name.rend()) 

to create the reverse string.

Then display it using cout.

Just an FYI, don't use gotos...

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: