如何在C ++中向后打印字符串?

时间:2014-02-06 20:52:33

标签: c++ string

我应该向后打印一个字符串输入。例如:

输入要反转的字符串:字符串
gnirts

这是我到目前为止所做的:

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string input;

    cout<<"Enter the string to reverse: " << endl;
    cin>>input;

    int size = input.length();

    for(int i=size; i>0; i--)
    {
        cout<<input[i];
    }

    return 0;
}

2 个答案:

答案 0 :(得分:3)

您的初始数组索引指向\0,您需要类似于

的内容
for(int i=size-1; i>=0; i--) // <-- like this

for(int i=size; i>0; i--)
{
  cout<<input[i-1]; // <-- like this
}

或者您可以使用reverse

#include <algorithm> // <-- add this include
std::reverse(input.begin(), input.end()); // <-- reverse the input string.

答案 1 :(得分:2)

最简单的方法是使用标准算法std :: reverse_copy

std::reverse_copy( input.begin(), input.end(), std::ostream_iterator<char>( std::cout ) ):
std::cout << std::endl;

这是最简单的方法,因为你不会在循环的控制语句中出错。:)

编辑:我忘了指出你也可以使用算法std :: copy。

std::copy( input.rbegin(), input.rend(), std::ostream_iterator<char>( std::cout ) );
std::cout << std::endl;

您也可以使用临时对象。例如

std::cout << std::string( input.rbegin(), input.rend() ) << std::endl;

如果要使用循环,则正确的循环将显示

for ( std::string::size_type i = input.size(); i != 0; )
{
   std::cout << input[--i];
}
std::cout << std::endl;

for ( std::string::size_type i = input.size(); i != 0; --i )
{
   std::cout << input[i - 1];
}
std::cout << std::endl;