#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;
}
- Why the "zsuidakrA" is being displayed before "Your reverse name
is" although I have coded like
cout<<" Your reverse name is "<<name[i]<<endl; - 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...
user2963345
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..
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";
}
}
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.
来源:https://stackoverflow.com/questions/52964280/reverse-the-string-in-c
