C 程序 需要帮助修复我的单词排序程序代码

标签 c arrays sorting

嗨,我对 C 语言还是个新手,并且已经在这个单词排序程序上工作了一段时间了。指导方针是:

编写一个程序,对用户输入的一系列单词进行排序。假设每个单词的长度不超过 20 个字符。当用户输入空词时停止阅读。使用指针数组(使用 read_line 函数)将每个单词存储在动态分配的字符串中。读取所有行后,对数组进行排序。然后使用循环按排序顺序打印单词。

我似乎遇到的问题是程序会接受单词,但是当我输入空单词时,它会转到新行并且没有任何反应。帮助或建议将不胜感激。这是到目前为止我的代码。

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


#define LEN 20
#define LIM 20

int read_line(char str[], int n);
void sort_str(char *list[], int n);
int alpha_first(char *list[], int min_sub, int max_sub);


int main(void)
{
    char *list[LIM];
    char *alpha[LIM];
    char word_str[LEN];
    int word, i, j,  num_count = 0;

    for(;;){

        printf("Enter a word: ");
        scanf("%s", &word);
        if(word == NULL)
            break;
        else
            read_line(word_str, LEN);
            list[i] = malloc(strlen(word_str) + 1);
            strcpy(list[i], word_str);
            alpha[i] = list[i];     
    }


    sort_str(alpha, i);

        for(i = 0; i < num_count; ++i){
        printf("Sorted: ");
        puts(list[i]);
    }   

    return (0);
}

int read_line(char str[], int n)
{
    int ch, i = 0;

    while ((ch = getchar()) != '\n')
        if (i < n)
            str[i++] = ch;
    str[i] = '\0';
    return i;
}

void sort_str(char *list[], int n)
{

    int   i, index_of_min; 
    char *temp;

    for  (i= 0;  i < n - 1;  ++i) {
        index_of_min = alpha_first(list, i, n - 1);

        if (index_of_min != i) {
            temp = list[index_of_min];
            list[index_of_min] = list[i];
            list[i] = temp;
        }
    }
}


int alpha_first(char *list[], int min_sub, int max_sub){
    int i, first;

    first = min_sub;
    for(i = min_sub + 1; i <= max_sub; ++i){
        if(strcmp(list[i], list[first]) < 0){
           first = i;
        }
   }
return (first);
}

最佳答案

你的逻辑流程有缺陷。如果输入了一个单词,则 scanf() 将从标准输入中获取它,并将一个以 null 结尾的字符串存储在整数“word”的地址处。输入任何超过 3/7 个字符(32/64 位,允许空终止符),将开始损坏堆栈。 read_line() 将只从 stdin 读取行终止符(假设 UB 不会先将其炸毁)。

关于C 程序 需要帮助修复我的单词排序程序代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30223488/

相关文章:

php - 字母数字数组排序(警告 : spaces as a thousands separator in numbers)

c - 如何找到某种类型的所有赋值表达式

c - C语言中如何防止非数字输入?

c - 如何在 C 中的字符串中获取井号(或哈希)符号?

c - 符号常量的意义何在?

c++ - 尝试对结构 A-Z 文件进行排序时出现排序函数错误

php - JS 数组转 PHP

c# - 从 mysql 查询中读取 PHP 数组作为 C# 中的字符串

javascript - 堆的算法返回数组而不是打印

python - 如何按英文日期格式排序而不是美式 pandas .sort()