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

如何将文件传入函数并将内容存储到数组(C++入门作业)

解决方法:使用给定ReadFile函数读取命令行传入的文件内容

你当前main函数里的核心问题是提前手动打开了文件,但教授提供的ReadFile函数设计逻辑是直接接收文件名、自行完成文件打开与读取操作,而且你定义的ifstream fileName还和函数参数名冲突,属于多余的错误操作。下面是修正后的完整代码与关键步骤:

1. 修正main函数逻辑

不需要手动打开文件,只需准备好存储数据的数组,直接把命令行参数里的文件名传给ReadFile即可:

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

// 教授提供的不可修改的函数声明
bool ReadFile(string fileName, string data[], const int maxArraySize);

int main(int argc, char* argv[])
{
    if (argc < 3)
    {
        cout << "Error! Not enough file names. Expecting 2!" << endl;
        return -1;
    }

    const int SIZE_DATA = 120; 
    // 准备两个数组,分别存储年份和冠军球队名称
    string years[SIZE_DATA];
    string champions[SIZE_DATA];

    // 读取年份文件
    if (!ReadFile(argv[1], years, SIZE_DATA)) {
        cout << "Failed to read year file: " << argv[1] << endl;
        system("pause");
        return -1;
    }
    cout << "Successfully read year file: " << argv[1] << endl;

    // 读取冠军球队文件
    if (!ReadFile(argv[2], champions, SIZE_DATA)) {
        cout << "Failed to read champion file: " << argv[2] << endl;
        system("pause");
        return -1;
    }
    cout << "Successfully read champion file: " << argv[2] << endl;

    // 可选:添加测试逻辑,比如打印前5组数据验证读取结果
    for (int i = 0; i < 5; ++i) {
        cout << "Year: " << years[i] << ", Champion: " << champions[i] << endl;
    }

    system("pause");
    return 0;
}

2. 实现ReadFile函数的核心逻辑

教授给出的函数是空实现,你需要补全文件读取的逻辑,同时处理文件打开失败、读取行数不超过数组容量的情况:

bool ReadFile(string fileName, string data[], const int maxArraySize)
{
    ifstream file(fileName);
    // 检查文件是否成功打开
    if (!file.is_open()) {
        return false;
    }

    string line;
    int index = 0;
    // 逐行读取内容,直到文件结束或数组存满
    while (getline(file, line) && index < maxArraySize) {
        data[index] = line;
        index++;
    }

    file.close();
    // 返回读取结果:至少读取到一行数据则判定为成功
    return index > 0;
}

关键注意点

  • 不要提前打开文件:ReadFile的设计目标就是封装文件IO操作,直接传入命令行参数里的文件名即可,无需手动打开。
  • 数组容量匹配:用const int SIZE_DATA定义数组大小,确保和两个文件的行数一致,避免越界。
  • 错误处理:通过ReadFile的返回值判断读取是否成功,在main函数中做对应的错误提示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 02:34:57