简体   繁体   中英

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.

The string is a null-terminated string. You are copying the null character to the beginning of the reversed string. This tells the system that they string is terminated at the first character.

You could use this code instead.

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

Here only the characters before the null character are copied and then the null character is added at the end.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM