反转C++中的字符串 [英] Reverse the string in C++

查看:74
本文介绍了反转C++中的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#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. 为什么 zsuidakrA" 显示在 您的反向名称之前是" 虽然我已经像 cout<<"您的反向名称是<<name[i]<<endl;
  2. 对于 cout<<name[i]<<" 你的反向名称是 "<<endl; 这一行,我只找到了您的反向名称是",但没有名称.为什么?
  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())

创建反向字符串.

然后使用cout显示它.

仅供参考,不要使用gotos...

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

这篇关于反转C++中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆