项目场景:
在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;
}