Reverse the string in C++

柔情痞子 提交于 2019-12-06 13:37:56

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!