Reverse the string in C++

2019-05-18 08:37发布

问题:

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

  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?

回答1:

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



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



回答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";
    }
}


回答4:

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.