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

C++如何将考试答案文件首行读取到字符数组中?

问题分析与解决方案

两种尝试的错误原因

第一种尝试

  • 字符数组answers[NUM_QUESTIONS]大小设置不足:getline读取char数组时,第二个参数代表缓冲区最大容量(包含字符串结束符\0),实际最多读取NUM_QUESTIONS-1个字符。若首行答案长度等于或超过NUM_QUESTIONS,getline会因未读取到换行符设置流的failbit,导致后续读取失效,第二次调用getline时输出空字符串。
  • 未检查文件是否成功打开,存在潜在风险。

第二种尝试

  • 错误调用getline函数:你将分隔符'\n'作为第二个参数传入,但getline的char数组版本第二个参数应为缓冲区大小(streamsize类型)。'\n'的ASCII码是10,相当于限制最多读取9个字符,导致首行内容被截断。

正确解决方案

方案1:使用足够大的char数组

确保缓冲区能容纳整行内容(含结束符\0),同时添加文件打开检查:

#include <iostream>
#include <fstream>
#include <cstring>

const int MAX_LINE = 100; // 设置足够大的缓冲区,适配所有行的长度

using namespace std;

int main() {
    char answers[MAX_LINE];
    ifstream infile;

    infile.open("Ch8_Ex6Data.txt");
    if (!infile.is_open()) {
        cerr << "无法打开目标文件" << endl;
        return 1;
    }

    // 读取首行答案密钥
    infile.getline(answers, MAX_LINE);
    cout << "答案密钥:" << answers << endl;

    // 循环读取后续学生作答行
    char student_data[MAX_LINE];
    while (infile.getline(student_data, MAX_LINE)) {
        cout << "学生作答:" << student_data << endl;
    }

    infile.close();
    return 0;
}

若确定答案密钥长度固定为NUM_QUESTIONS,可将缓冲区大小设为NUM_QUESTIONS + 1(预留\0的位置):

const int NUM_QUESTIONS = 20;
char answers[NUM_QUESTIONS + 1]; // 21个元素,容纳20个字符+结束符
infile.getline(answers, NUM_QUESTIONS + 1);

方案2:使用std::string(更推荐)

std::string会自动调整长度,无需手动管理缓冲区,代码更简洁安全:

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

using namespace std;

int main() {
    string answers;
    ifstream infile("Ch8_Ex6Data.txt");

    if (!infile) {
        cerr << "无法打开目标文件" << endl;
        return 1;
    }

    // 读取首行答案密钥
    getline(infile, answers);
    cout << "答案密钥:" << answers << endl;

    // 循环读取后续学生作答行
    string student_data;
    while (getline(infile, student_data)) {
        cout << "学生作答:" << student_data << endl;
    }

    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 21:49:57