簡體   English   中英

打印 C 中的反向輸入列表

[英]Printing a list of reversed input in C

我是 C 的新手,我的目標是從用戶那里獲取多個輸入,將它們全部添加到它們之間有空格的字符串中,然后將其反轉並打印在一行上。

我已經嘗試了下面的代碼,但我仍然得到相同的錯誤 Segmentation Fault。 不要介意 fflush(stdout),這是因為我將 bash 用於 windows。

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


  void reverse(char *x, int begin, int end)
  {
     char c;
     if (begin >= end)
        return;
     c          = *(x+begin);
     *(x+begin) = *(x+end);
     *(x+end)   = c;
     reverse(x, ++begin, --end);
  }

  int main()
  {
      int note;
      char *str =" ";
      char ch ;
      while (note > 0)
      {
          printf ("enter input must be a positive int to stop enter a ngative int: ");
          fflush( stdout );
          scanf ("%f" ,&note);
          itoa(note, ch, 10);
          strcat(str,ch);
      }
      reverse(str, 0, strlen(str)-1);
      printf("%s", str);
      fflush( stdout );
      return 0;
  }

這是一個更新的版本,但我不明白如何修復錯誤::41:39:注意:預期的'const char *'但參數是'char'類型

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


  void reverse(char *x, int begin, int end)
  {
     char c;
     if (begin >= end)
        return;
     c          = *(x+begin);
     *(x+begin) = *(x+end);
     *(x+end)   = c;
     reverse(x, ++begin, --end);
  }

  int main()
  {
      int ret;
      char *mot =" ";
      char ch ;
      while (1)
      {
          printf ("input : ");
          fflush( stdout );
          ret = scanf ("%d" ,&ch);
          if (ret != 1) break;
          strcat(mot,ch);
      }
      reverse(mot, 0, strlen(mot)-1);
      printf("%s", mot);
      fflush( stdout );
      return 0;
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM