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

C++读取文件字符串存入vector时push_back无匹配函数报错如何解决

error: no matching function for call to ‘std::vector<std::__cxx11::basic_string >::push_back(std::ifstream&)

错误原因

你定义的std::vector<std::string>容器只能存储std::string类型的元素,但你在调用push_back方法时直接传入了std::ifstream文件流对象,两种类型不匹配,编译器找不到对应入参的push_back重载函数,因此抛出该错误。

修复方案

你需要先从文件流中读取字符串内容,再将读取到的字符串存入vector中,参考修正后的代码如下:

#include <fstream>
#include <vector>
#include <string> // 新增std::string对应的头文件

const unsigned short numOfStrings=5;

void ReadFromFile (std::ifstream& thisin, std::vector<std::string>& thisData)
{
    std::string tempStr;
    // 按空格/换行分隔读取字符串,读到文件末尾自动结束
    while (thisin >> tempStr) {
        thisData.push_back(tempStr);
    }
    // 如果你需要固定读取numOfStrings个字符串,可以替换为如下循环
    // for(int i=0; i<numOfStrings && thisin >> tempStr; ++i) {
    //     thisData.push_back(tempStr);
    // }
}

int main ()
{
    // 调用示例
    std::ifstream inFile("你的文件路径.txt");
    std::vector<std::string> data;
    if (inFile.is_open()) {
        ReadFromFile(inFile, data);
        inFile.close();
    }
    return 0;
}

额外说明:

  • 如果需要按行读取文件内容,将循环中的thisin >> tempStr替换为std::getline(thisin, tempStr)即可,注意如果之前使用过>>读取内容,需要先调用ignore()清理残留的换行符,避免读到空行。
  • 传入文件流前建议先判断是否打开成功,避免读取空内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 21:12:04