c - Reversing an input string -


i trying capture user input string, display string in reverse order next initial string. code follows:

char str[300], revstring[300]; int i, strlen;    int main(void) {       printf("enter string: ");                 //prompt user input string     gets(str);      (i = 0; str[i] != null; i++) {          //get length of string         strlen += 1;     }      (i = 0; <= strlen; i++) {         revstring[i] = str[strlen - i];     }      printf("\n\nthe palindrome of input %s%s\n\n\n", str, revstring);      return 0; } 

when run program however, see nothing after initial string. come python background maybe thinking in of python mindset, feel should work.

after loop

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

str[strlen] equal terminating 0 '\0'. , next loop starts writing 0 in first element of array revstring when i equal 0.

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

as result nothing displayed.

also should not forget append result string terminating zero.

take account function gets unsafe , not supported more c standard. better use standard function fgets. using should remove appended new line character.

the program can written

#include <stdio.h>  #define n   300  int main( void )  {     char str[n], revstring[n];      printf( "enter 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 = 0;     ( ; != length; i++ ) revstring[i] = str[length - - 1];      revstring[i] = '\0';      printf("\n\nthe palindrome of input %s%s\n\n\n", str, revstring);      return 0; } 

its output might like

enter string: hello, froobyflake  palindrome of input hello, froobyflakeekalfyboorf ,olleh 

Comments

Popular posts from this blog

php - How to display all orders for a single product showing the most recent first? Woocommerce -

asp.net - How to correctly use QUERY_STRING in ISAPI rewrite? -

angularjs - How restrict admin panel using in backend laravel and admin panel on angular? -