You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从STDIN读取单词并存入数组以进行后续排序?

从标准输入读取单词并存入可排序数组的实现方法

你当前的代码只能读取整行输入,要拆分出单个单词并存入可用于排序的数组,可按以下步骤实现:

核心思路

  1. 用getline()读取整行输入
  2. 用strtok()拆分整行内容为单个单词
  3. 用动态指针数组存储单词(按需扩容,适配不确定的单词数量)
  4. 最后用标准库函数完成排序

完整实现代码

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

int main() {
    printf("Please enter words to sort:\n");
    char *line = NULL;
    size_t len = 0;
    ssize_t lineSize = getline(&line, &len, stdin);
    
    // 处理读取失败的情况
    if (lineSize == -1) {
        perror("Failed to read line");
        free(line);
        return 1;
    }

    // 初始化动态指针数组存储单词
    char **words = NULL;
    int wordCount = 0;
    int capacity = 2; // 初始容量,可按需调整

    // 第一次分配数组内存
    words = malloc(capacity * sizeof(char*));
    if (words == NULL) {
        perror("Failed to allocate memory");
        free(line);
        return 1;
    }

    // 拆分字符串为单词,分隔符包含空格、制表符、换行符
    char *token = strtok(line, " \t\n");
    while (token != NULL) {
        // 数组容量不足时扩容
        if (wordCount >= capacity) {
            capacity *= 2;
            char **temp = realloc(words, capacity * sizeof(char*));
            if (temp == NULL) {
                perror("Failed to reallocate memory");
                // 提前清理已分配的内存,避免泄漏
                for (int i = 0; i < wordCount; i++) {
                    free(words[i]);
                }
                free(words);
                free(line);
                return 1;
            }
            words = temp;
        }

        // 为单个单词分配内存并复制内容
        words[wordCount] = malloc(strlen(token) + 1);
        if (words[wordCount] == NULL) {
            perror("Failed to allocate memory for word");
            // 清理已分配资源
            for (int i = 0; i < wordCount; i++) {
                free(words[i]);
            }
            free(words);
            free(line);
            return 1;
        }
        strcpy(words[wordCount], token);
        wordCount++;

        // 继续拆分剩余内容
        token = strtok(NULL, " \t\n");
    }

    // 输出原始单词(测试用)
    printf("You entered %d words:\n", wordCount);
    for (int i = 0; i < wordCount; i++) {
        printf("%s\n", words[i]);
    }

    // 用qsort排序字符串数组,搭配strcmp作为比较函数
    qsort(words, wordCount, sizeof(char*), 
          (int (*)(const void*, const void*))strcmp);

    // 输出排序后的单词
    printf("\nSorted words:\n");
    for (int i = 0; i < wordCount; i++) {
        printf("%s\n", words[i]);
    }

    // 释放所有动态分配的内存
    for (int i = 0; i < wordCount; i++) {
        free(words[i]);
    }
    free(words);
    free(line);
    return 0;
}

关键细节说明

  • strtok()的使用:第一次调用传入原始字符串,后续调用传入NULL即可继续拆分剩余内容,分隔符可根据需求调整。
  • 动态数组扩容:通过realloc()实现数组容量的动态增长,避免内存浪费或溢出。
  • 内存管理:所有动态分配的内存必须手动释放,防止内存泄漏。
  • 排序逻辑:直接使用标准库的qsort()函数,搭配字符串比较函数strcmp即可完成排序。

内容的提问来源于stack exchange,提问作者Dakota Kellogg

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 04:46:11