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

C++读取文本文件时仅识别两行而非三行的问题排查

解决std::getline无法读取末尾空行的问题

你的代码使用while (std::getline(inputFile, line))循环读取文件行,这个循环会在getline返回false时终止——触发条件包括到达文件末尾(EOF)或读取出错。但如果文本文件的最后一行是空行且没有结尾的换行符,getline会直接返回false,不会将这个空行存入std::vector,导致你只能读到两行内容。

修改后的代码

bool getData(const std::string& inputLocation, std::vector<std::string>& data)
{
    std::ifstream inputFile(inputLocation);

    if (!inputFile.is_open())
    {
        return false;
    }

    std::string line;
    bool readSuccess = true;

    do {
        std::getline(inputFile, line);
        data.push_back(line);
        // 仅在非EOF原因导致读取失败时,标记错误
        if (inputFile.fail() && !inputFile.eof()) {
            readSuccess = false;
            break;
        }
    } while (!inputFile.eof());

    inputFile.close();
    
    return readSuccess;
}

说明

改用do-while循环后,会先执行一次读取操作并将内容存入vector,再判断是否到达文件末尾。这样无论文件是否以换行符结尾,末尾的空行都会被正确读取。同时代码保留了错误处理逻辑:如果遇到IO错误(如文件损坏、权限问题),会返回false,保证函数的可靠性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 01:06:14