简体   繁体   中英

Reading in strings

I am asked to take a string and reverse it, but I'm not sure how to do it, so I tried simply reading in the string, and reprinting it out. But I am having trouble with that too. Could somebody point me in the right direction?

#include <stdio.h>
#include <stdlib.h>

int main()
{
  char* word[64];
  printf("Input: ");
  fgets(*word, 256, stdin);
  printf("Reversed: %s\n", *word);

  return 0;
} //end main

Change this

  char* word[64];
  printf("Input: ");
  fscanf(stdin, "%s", *word);
  printf("Reversed: %s\n", *word);

to

  char word[64]; // remove the "*" so it's a char array, not array of char*
  printf("Input: "); // no change
  fscanf(stdin, "%s", word); // remove the * so you point to the array
  printf("Reversed: %s\n", word); // print out the string

Your fgets version should be

  char word[64];
  printf("Input: ");
  fgets(word, 64, stdin);
  printf("Reversed: %s\n", word);

To reverse the string, you can use for and a swap

   for( i = 0 ; i < len/2 ; i++ )   
   {        
       tmp = s[i];
       s[i] = s[len-i];   
       s[len-] = tmp;         
   }

len is the length of the string, you can use function strlen to calculate. tmp is a temperary variable.

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