Reverse of String

Program : Reverse String Without Using Library Function [ Strrev ]

#include <stdio.h>
#include <string.h>

#define BUFFER_SIZE 100
char buff[BUFFER_SIZE];
int main()
{
        char str[20];
        printf("Enter The string is : ");
        /* gets(str);   // unsafe! */
        fgets( str, sizeof(buff), stdin );   // safe
        int i=0, j=0;
        j = strlen(str)-1;
        while(i<j)
        {
                char tmp;
                tmp = str[j];
                str[j--]=str[i];
                str[i++]= tmp;
        }
        printf("The reverse of string is : %s\n", str);
        return 0;
}


Output :    Enter The string is : Interstellar
                   The reverse of string is : 
                    ralletsretnI

Remember : gets(str): This statement will give warning as : warning: the `gets' function is dangerous and should not be used.

In order to use gets safely, you have to know exactly how many characters that you will be reading so you can make your buffer large enough. You will only know that if you know exactly what data you will be reading.

Instead of using gets, you want to use fgets, which has the signature :

char* fgets(char *string, int length, FILE * stream);
(fgets, if it reads an entire line, will leave the '\n' in the string as in above output; you'll have to deal with that)



No comments:

Post a Comment