简体   繁体   中英

Reversing string in C using for loop

I'm a beginner in C and I don't understand why my code isn't working. The aim is simply just to reverse a string.

char word[20];
int i, len;

printf("Enter word: ");
    scanf("%s", &word);

len = strlen(word);

printf("String reversed: "); 
for (i = len-1; i >= 0; i--){
    printf("%s", word[i]);
}

In

 printf("%s", word[i]); 

%s is a wrong format because you write a character, not a string

Out of that :

  • the natural type for an index is size_t not int , use size_t for both i and len , and in that case change the loop to use index without supposing it can be negative

  • if the input string has more than 19 characters scanf will write out of word with an undefined behavior, limit the size using the format %19s (19 rather than 20 to have the place for the ending null character)

  • word is an array, do not use a '&' to give its address in scanf

  • check the result of scanf if you want to detect EOF

  • flush the output writing a newline after the loop

So a possible way is :

char word[20];

printf("Enter word: ");
if (scanf("%19s", word) == 1) {   
  printf("String reversed: "); 

  for (size_t i = strlen(word); i != 0; i--){
    printf("%c", word[i-1]);
  }
  putchar('\n');
}

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