使用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
相关产品推荐
相关产品推荐

