开发者

reversing of a string

#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;
        tem开发者_开发问答p=b[j-i-1];
        b[j-i-1]=b[i];
        b[i]=temp;
    }
    return b;
}

This program is giving no compile time error.But it does give run time error and does not give desired output. Please explain the cause.As I am not that much good in C++ so please forgive me if my question is not upto mark.


You are not allocating memory for the string. gets doesn't allocate memory for you, so you're just reading into some random location - results are undefined.

Apart from that, there are more problems:

  • This is tagged C++ but it's more like C with cout (using string would be a better idea)
  • You are using gets instead of fgets. gets is quite dangerous and should be avoided.


You need to use 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;
}

The Standard provides string handling that isn't insane like the C-strings you're trying to use, and it also provides reverse iteration quite trivially. In this model you don't have to allocate your own memory or do your own reversal.


You need to allocate space for the first string otherwise you are pointing to the ether and overwriting God only knows what space. But, to be more idiomatic C++ may I suggest you use a standard string? Simply replace the char* with std::string.


In addition to the previous answers, you are actually reversing your string twice. You have to walk only half of the string.


Check the reference on the proper usage of gets(). You can't pass it an uninitialized char* and expect anything good to happen. You might have better luck with:

char a[256];
cout<<"enter string"<<endl;
gets(a);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜