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

C++如何从文件读取单词存入动态分配数组

修正后的动态内存分配实现方案

原有代码存在的问题

  • main函数中调用loadData()后直接return 0,后续的文件读取逻辑永远不会执行
  • while (!dataFile.eof())用法错误,会触发最后一行数据重复读取的问题
  • 小写转换逻辑放在读取循环内部,会对数组内已有元素重复执行转换,性能损耗严重
  • 固定大小数组最多只能存100个单词,超出长度会发生数组越界

手动动态分配实现(适配指针练习需求)

#include <iostream>
#include <fstream>
#include <algorithm>
#include <cctype>
#include <string>

using namespace std;

void loadData() {
    string fileName;
    // 动态数组相关变量
    int capacity = 100; // 初始容量
    int count = 0; // 已存储的单词数量
    string* wordArray = new string[capacity]; // 动态分配初始数组

    cout << "请输入要处理的txt文件名,包含.txt后缀:" << endl;
    cin >> fileName;

    ifstream dataFile(fileName);
    if (dataFile.fail()) {
        cerr << fileName << " 无法打开" << endl;
        delete[] wordArray; // 退出前释放已分配的内存
        exit(-1);
    }

    string tempWord;
    // 正确的读取逻辑,读入成功才继续处理
    while (dataFile >> tempWord) {
        // 容量不足时扩容
        if (count >= capacity) {
            int newCapacity = capacity * 2;
            string* newArray = new string[newCapacity];
            // 拷贝旧数组元素到新数组
            for (int i = 0; i < capacity; i++) {
                newArray[i] = wordArray[i];
            }
            // 释放旧数组
            delete[] wordArray;
            // 更新指针和容量
            wordArray = newArray;
            capacity = newCapacity;
        }
        // 转换为小写
        transform(tempWord.begin(), tempWord.end(), tempWord.begin(),
            [](unsigned char c) { return tolower(c); });
        // 存入数组
        wordArray[count] = tempWord;
        count++;
    }
    dataFile.close();

    // 这里可以添加对wordArray的使用逻辑,比如打印所有单词
    cout << "共读取到" << count << "个单词,部分示例:" << endl;
    for (int i = 0; i < min(10, count); i++) {
        cout << wordArray[i] << " ";
    }
    cout << endl;

    // 所有使用结束后释放动态数组,避免内存泄漏
    delete[] wordArray;
}

int main()
{
    loadData();
    return 0;
}

关键逻辑说明

  • 动态数组通过string*类型的指针管理,用new[]分配内存,delete[]释放内存,注意分配和释放要配对使用
  • 扩容采用两倍扩容的策略,均摊时间复杂度和固定数组接近,不会频繁触发扩容操作
  • 读取逻辑直接判断dataFile >> tempWord的返回值,避免eof用法导致的重复读取问题
  • 小写转换仅对当前新读取的单词执行,无需遍历整个数组,性能提升明显

简化方案(生产环境推荐)

如果不需要练习指针,直接使用STL容器std::vector<std::string>即可,容器会自动处理内存分配、扩容和释放,无需手动管理,代码更简洁安全。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 11:27:02