c - 单词反转程序。由于空行而缺少单词

标签 c reverse

我有一个可以反转单词的程序。问题是当我输入一个空行(只需按 Enter)时,输出上缺少单词(即在空行之后)。我应该在代码中做什么?

例如:

输入:

  • aaaa
  • zzzz
  • cccc
  • ffff

输出:

  • aaaa
  • cccc
  • zzzz

缺少“ffff”:(

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

#define N_MAX 100000

int compare(const void *a, const void *b)   /* funkcja uzywana przy qsort */
{
    return strcmp(*((char**) a), *((char**) b));
}


int main()
{
    int i=0, j;
    char* Tekst[N_MAX];

    char c;
    while ((c = getchar()) != EOF)
    {
        char tab1[1000]={0};    
        char tab2[1000]={0}; 

        tab1[0] = c;
        gets(tab2);
        strcat(tab1, tab2);

        if (c!='\n')
        {                      
            Tekst[i] = (char*)malloc((strlen(tab1)+1)*sizeof(char));
            strcpy(Tekst[i], tab1);
            i++;
        }
    }

    qsort(Tekst, i, sizeof(char *), compare); 

    puts ("\n\n");
    for (j=0; j<i; j++)
    {
        puts(Tekst[j]);
    }
    return 0;
}

最佳答案

这里不需要 getchar()strcat

您可能想要这个:

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

#define N_MAX 100000

int compare(const void *a, const void *b)   /* funkcja uzywana przy qsort */
{
  return strcmp(*((char**)a), *((char**)b));
}

int main()
{
  int i = 0, j;
  char* Tekst[N_MAX];

  while (1)
  {
    char tab2[1000] = { 0 };

    if (fgets(tab2, 1000, stdin) == NULL)
      break;   // on EOF fgets returns NULL

    tab2[strlen(tab2) - 1] = 0;   // get rid of \n at the end of the string

    Tekst[i] = (char*)malloc((strlen(tab2) + 1) * sizeof(char));
    strcpy(Tekst[i], tab2);
    i++;
  }

  qsort(Tekst, i, sizeof(char *), compare);

  puts("\n\n");
  for (j = 0; j<i; j++)
  {
    puts(Tekst[j]);
  }
  return 0;
}

如果您确实想使用 gets 而不是 `fgets,请替换

if (fgets(tab2, 1000, stdin) == NULL)

if (gets(tab2) == NULL)

关于c - 单词反转程序。由于空行而缺少单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41741843/

相关文章:

c - 是否可以保真地将浮点 double 往返到两位十进制整数?

c++ - 如何反转字符串中的所有单词? C++

c++ - 我的反向单链表函数代码有什么问题?

javascript - 输出原始数组的反向和连接函数

c# - 在 C 库调用中保留对 .NET 对象的 C++/CLI 句柄

c++ - wchar_t 对字符串的位操作

c++ - 原子比较、多处理器、C/C++ (Linux)

c - 为什么我用 C union 得到这个输出?

windows - 使用 AWK 或 SED 等命令行工具反转文本文件中的字符串

java - JAVA中单词末尾大写字母后如何反转单词?