翻转一个字符串

Gau*_*mar 2 c++

#include<iostream>
#include<string.h>
using namespace std;
char * reverse (char *);
int main()
{
    char * a;
    cout<<"enter string"<<endl;
    gets(a);
    cout<<a;
    cout<<"the reverse of string is"<<reverse(a);
    return 0;
}
char * reverse (char * b)
{
    int i,j=strlen(b);
    for(i=0;b[i]!='\0';i++)
    {
        char temp;
        temp=b[j-i-1];
        b[j-i-1]=b[i];
        b[i]=temp;
    }
    return b;
}
Run Code Online (Sandbox Code Playgroud)

该程序没有给出编译时错误.但是它确实给出了运行时错误并且没有给出所需的输出.请解释原因.由于我在C++方面不是很好,所以如果我的问题没有达到标记,请原谅我.

cni*_*tar 7

您没有为字符串分配内存.gets没有为你分配内存,所以你只是读入一些随机位置 - 结果是未定义的.

除此之外,还有更多问题:

  • 这是标记的C++,但它更像C与Cout(使用string会是一个更好的主意)
  • 你正在使用gets而不是fgets.gets是非常危险的,应该避免.


Pup*_*ppy 6

你需要使用std::string.

#include <iostream>
#include <string>
#include <algorithm>
#include <iterator>
int main()
{
    std::string a;
    std::cout<<"enter string"<<endl;
    std::cin >> a;
    std::cout << "The reverse of a string is ";
    std::copy(a.rbegin(), a.rend(), std::ostream_iterator<char>(cout));
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

标准提供的字符串处理并不像您尝试使用的C字符串那样疯狂,并且它还提供了非常简单的反向迭代.在此模型中,您不必分配自己的内存或进行自己的反转.

  • "+ 1"来自我的真正的C++解决方案.(替代方案,对初学者来说可能更容易)是使用`std :: reverse()`和`std :: cout << a`.) (2认同)