Gautam Kumar
Gautam Kumar

Reputation: 1170

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;
        temp=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.

Upvotes: 2

Views: 320

Answers (5)

Puppy
Puppy

Reputation: 146910

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.

Upvotes: 6

RocketR
RocketR

Reputation: 3766

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

Upvotes: 2

aroth
aroth

Reputation: 54806

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);

Upvotes: 1

cnicutar
cnicutar

Reputation: 182619

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.

Upvotes: 7

wheaties
wheaties

Reputation: 35970

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.

Upvotes: 2

Related Questions