Reverse String C

六月ゝ 毕业季﹏ 提交于 2019-12-13 07:47:55

问题


I'm trying to create a program that reads text from a file that was previously created, inverts it, and writes to another file. The code I have now allows me to invert single words, but stops whenever there is a space or a paragraph. I could use some help in overcoming this problem. This is the code I have so far:

#include <stdio.h>
#include <string.h>

int main()
{
  int c, d;
  FILE *fich1, *fich2;
  char string [100], *inicio, *fim, tempo;

  fich1 = fopen("FicheiroInicial.txt", "rt");
  if (fich1 == NULL)
    {
      printf ("Erro - Nao foi possivel abrir o ficheiro\n");
      return (-1);
    }
  fscanf (fich1, "%s", string);
  fclose (fich1);
  inicio = string;
  fim = inicio + strlen(string) - 1;

  while (fim > inicio)
    {
      tempo = *inicio;
      *inicio = *fim;
      *fim = tempo;

      ++inicio;
      --fim;
    }  

  fich2 = fopen("FicheiroFinal.txt", "wt");
  fprintf (fich2, "%s", string);
  fclose (fich2);
  printf ("%s", string);

  return 0;
}

Thanks in advance!


回答1:


I believe fscanf() will only give you a word at a time. you will need to iterate over it until it returns EOF (end of file)



来源:https://stackoverflow.com/questions/20032262/reverse-string-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!