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

C++使用getline()读取文件跳行、内容重复死循环问题求解

问题根因与修复方案

核心问题1:死循环导致重复输出

你的主函数中fileStreamState仅在输入文件打开时赋值为1,后续循环过程中从未更新,即使文件读取到末尾、流状态失效,循环也不会终止。且输入流失效后,readInfo不会修改结构体内容,就会持续输出最后一次读取到的有效数据,必须强制终止。

核心问题2:多余的ignore调用导致跳行

getline函数本身就会读取整行内容,并且自动丢弃行末的换行符\n,你在每次getline之后额外调用inFile.ignore(INT_MAX, '\n'),会直接跳过下一行的全部内容,最终导致读取顺序完全错乱、出现跳行。唯一需要保留ignore的场景是用>>读取zipcode之后:>>运算符只会读取数字内容,会把行末的\n留在输入缓冲区,后续getline会读到空行,所以这一步的ignore是必要的。

其他小问题

  • openOutputFile函数中,输出文件打开失败后,提示语错误要求用户输入「输入文件」名称,属于笔误,需要修正为输出文件。
  • 所有读取操作没有做状态校验,即使读取到文件尾、读取失败,程序依然会继续执行后续读取和输出逻辑。

修复步骤

1. 同步修改函数声明

将头部的readInfo函数声明修改为:

bool readInfo(ifstream& inFile, Info&);

2. 修改主函数循环逻辑

将原有的固定fileStreamState判断循环替换为根据读取结果判断的逻辑:

// 原有的fileStreamState变量可以删除
while (readInfo(inFile, person)) {
    printInfo(outFile, person);
}

3. 修正readInfo函数

移除所有多余的ignore调用,增加读取状态校验:

bool readInfo(ifstream& inFile, Info& record) {
    if (!getline(inFile, record.person.phoneNumber)) return false;
    cout << record.person.phoneNumber << endl;

    if (!getline(inFile, record.person.lastName)) return false;
    cout << record.person.lastName << endl;

    if (!getline(inFile, record.address.streetNum_Name)) return false;
    cout << record.address.streetNum_Name << endl;

    if (!getline(inFile, record.address.city)) return false;
    cout << record.address.city << endl;

    if (!getline(inFile, record.address.state)) return false;
    cout << record.address.state << endl;

    if (!(inFile >> record.address.zip_code)) return false;
    cout << record.address.zip_code << endl;

    // 仅保留这个ignore,处理>>运算符留下的换行符
    inFile.ignore(INT_MAX, '\n');
    if (!getline(inFile, record.person.firstName)) return false;
    cout << record.person.firstName << endl;

    return true;
}

4. 修正openOutputFile的错误提示

将输出文件打开失败后的输入提示:
cout << "Enter in the name of the input file: ";
修改为:
cout << "Enter in the name of the output file: ";

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 09:39:01