Froobyflake Froobyflake - 22 days ago 6
C Question

Reversing an input string

I am trying to capture a user input string, then display that string in reverse order next to the initial string. My code is as follows:

char str[300], revstring[300];
int i, strlen;



int main(void) {


printf("Enter a string: "); //Prompt user for input string
gets(str);

for (i = 0; str[i] != NULL; i++) { //Get length of string
strlen += 1;
}

for (i = 0; i <= strlen; i++) {
revstring[i] = str[strlen - i];
}

printf("\n\nThe palindrome of your input is %s%s\n\n\n", str, revstring);

return 0;
}


When I run the program however, I see nothing after the initial string. I come from a python background so maybe I am thinking about this in too much of a python mindset, but I feel like this should work.

Answer

After this loop

for (i = 0; str[i] != NULL; i++) {          //Get length of string
    strlen += 1;
}

str[strlen] is equal to the terminating zero '\0'. And the next loop starts from writing this zero in the first element of the array revstring when i is equal to 0.

for (i = 0; i <= strlen; i++) {
    revstring[i] = str[strlen - i];
}

As result nothing is displayed.

Also you should not forget to append the result string with the terminating zero.

Take into account that the function gets is unsafe and is not supported any more by the C Standard. It is better to use the standard function fgets. But using it you should remove the appended new line character.

The program can be written the

#include <stdio.h>

#define N   300

int main( void ) 
{
    char str[N], revstring[N];

    printf( "Enter a string: " );

    fgets( str, N, stdin );

    size_t  length = 0;
    while ( str[length] != '\0' && str[length] != '\n' ) ++length;

    if ( str[length] == '\n' ) str[length] = '\0';

    size_t i = 0;
    for ( ; i != length; i++ ) revstring[i] = str[length - i - 1];

    revstring[i] = '\0';

    printf("\n\nThe palindrome of your input is %s%s\n\n\n", str, revstring);

    return 0;
}

Its output might look like

Enter a string: Hello, Froobyflake

The palindrome of your input is Hello, FroobyflakeekalfyboorF ,olleH
Comments