linux使用C++编译报错 (error: no matching function for call to ‘std::basic_ifstream<char>::open(const))

本文介绍了在Linux环境下使用C++读取目录下label.txt文件内容时遇到的问题及解决方法。报错原因是不能直接将字符串类型的路径传递给ifstream的open方法。解决方案是在调用open方法时,使用path.c_str()将字符串转换为C风格字符串,从而正确打开文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

项目场景:

        在linux环境下,想使用C++读取目录下的label.txt文件内容。


报错的代码:

#include <iostream>
#include<fstream>
#include <vector>
using namespace std;

std::vector<std::string> load_labels(const std::string &path) {
  std::ifstream file;
  std::vector<std::string> labels;
  file.open(path));
    if(file.is_open()){
        std::string line;
        while(getline(file, line)){
            labels.push_back(line);
        }
        file.close();
    }
    else{
        std::cout << "can not open label_file" << std::endl;
    }
  return labels;
}

int main(){
    std::string label_path = "label/label_list.txt";
    std::vector<std::string> word_labels = load_labels(label_path);
    std::cout<<"-------------------------label read successful-------------------------"<<std::endl;
    for (int i = 0; i < word_labels.size(); i++) 
        std::cout << word_labels[i] << ' ';
    return 0;
}

报错内容:

error: no matching function for call to 'std::basic_ifstream<char>::open(const string&)

        file.open(path));


解决方案:

报错原因:linux forums钟描述C++ ofstream::open won't accept string as a filename,

linux下会出问题原因就在于string不能直接作为fstream的参数直接传入(即使不在linux,我在windows下也会出现这个报错)。

修改读取的path后面加上一个类型定义即可

#include <iostream>
#include<fstream>
#include <vector>
using namespace std;

std::vector<std::string> load_labels(const std::string &path) {
  std::ifstream file;
  std::vector<std::string> labels;
  file.open(path.c_str());
    if(file.is_open()){
        std::string line;
        while(getline(file, line)){
            labels.push_back(line);
        }
        file.close();
    }
    else{
        std::cout << "can not open label_file" << std::endl;
    }
  return labels;
}

int main(){
    std::string label_path = "label/label_list.txt";
    std::vector<std::string> word_labels = load_labels(label_path);
    std::cout<<"-------------------------label read successful-------------------------"<<std::endl;
    for (int i = 0; i < word_labels.size(); i++) 
        std::cout << word_labels[i] << ' ';
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值