2
#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;
}

enter image description here

  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?
JeJo
  • 30,635
  • 6
  • 49
  • 88
Mr.Khan
  • 21
  • 1
  • 4
  • 1
    Possible duplicate of [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems) – Raedwald Oct 24 '18 at 08:41
  • 1
    What you have done is not called "reversing a string". It is called "printing a string in reverse order". When you reverse a string, you start with a string and end up with a different string. You don't print anything in process. If you want to test what you have done, you print the new string normally as you would print any other string. – n. m. could be an AI Oct 24 '18 at 08:54

4 Answers4

6

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...

Matthieu Brucher
  • 21,634
  • 7
  • 38
  • 62
3

You could use std::reverse to reverse it for you:

#include <iostream>
#include <cstdlib>
#include <algorithm> // std::reverse

int main(){
    std::string name;
    while(true) {
        std::cout << "Hey! Enter your name: " << std::flush;
        std::cin >> name;
        std::cout << "Your name is: " << name << "\n";
        std::reverse(begin(name), end(name));
        std::cout << "Your reverse name is: " << name << "\n";
    }
}
Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
2

Remove the last two cout statements. The reverse string is already printed by the cout statement inside the do-while loop. You can move the

cout<<" Your reverse name is "<<endl;

before the do statement if that is really required..

Paul Floyd
  • 5,530
  • 5
  • 29
  • 43
1

1) because you are printing name[i] in do while loop before your cout statement.

2) because value of i = -1 after it comes out of do while loop as ( i > -1) condition gets false, and name[-1] is probably printing nothing.