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

使用FILE*结合std::getline()出现类型不匹配编译错误的解决方案咨询

问题原因

编译报错的核心是C++标准库的std::getline仅接收std::basic_istream派生类作为输入源,你传入的C风格文件指针FILE*不属于该类型,因此触发类型不匹配错误。

解决方案

在保留FILE*用法的前提下,可以用C标准库的fgets函数逐行读取文件内容,再转换为std::string交给后续逻辑处理即可,原有拆分、插入map的逻辑不需要改动。

修改后完整代码
#include <iostream>
#include <map>
#include <sstream>
#include <string>
#include <limits>
#include <cstdio>
#include <cstring>

// 可根据实际业务中每行最大长度调整该值
#define BUF_SIZE 4096
#define PCI_MAPPING_PATH "/your/path/here" // 替换为实际路径

using namespace std;

int main()
{
    FILE *fpFile;
    map<string, string> mapOfPci;
    char readBuf[BUF_SIZE] = {0};
    std::string tempBuff = "";
    std::string line1 = "", line2 = "";
        
    fpFile = fopen(PCI_MAPPING_PATH, "r");
    
    if(!fpFile)
        // 原代码返回false会隐式转为0,属于正常退出码,建议改为非0代表异常
        return 1;
    
    while(fgets(readBuf, BUF_SIZE, fpFile) != nullptr){
        tempBuff = readBuf;
        // 去掉fgets读取到的末尾换行符
        if (!tempBuff.empty() && tempBuff.back() == '\n') {
            tempBuff.pop_back();
        }
        istringstream iSs(tempBuff);
        iSs >> line1;
        iSs.ignore(numeric_limits<std::streamsize>::max(), ':');
        iSs >> line2;
        mapOfPci.insert(make_pair(line1, line2)); 
    }
    for(const auto &m : mapOfPci){
        cout << m.first << " : " << m.second << "\n";
    }
    
    fclose(fpFile);
    return 0;
}
注意事项
  • 如果业务中存在超过BUF_SIZE长度的行,需要调大缓冲区数值,或者自行实现动态扩容的行读取逻辑,避免长行被截断导致数据异常。
  • 原有拆分逻辑默认line1中没有空白字符,如果你的业务场景中line1允许包含空格,需要调整拆分逻辑为直接查找:的位置再做子串切割。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 20:15:02