C++对参数1没有已知的转换-从文件中读取

C++ no known conversion for argument 1 - reading from a file

本文关键字:转换 文件 读取 参数 C++      更新时间:2023-10-16

我一直在开发一个文件读取器,它从文件内部读取数据并将其存储在字符串中。当我硬编码要打开的文件名时,我的代码会编译它应该如何编译,但当我试图从键盘读取文件时,我会得到错误"参数1从str到const没有已知的转换,我不知道为什么

#include <iostream>
#include <fstream>
#include <string>
int main() {
 string fileName;
 cout << "Enter the file name to be read: ";
 cin >> fileName;
 ifstream input_file(fileName);
 std::string line_; // string which text file contents will be stored in
 if(input_file.is_open()){ // validation to see if the file is open
   while(getline(input_file, line_)){
     std::cout<<line_<< 'n'; //prints the contents of the file into the console
   }
  input_file.close();
 }
 else {
   std::cout<<"File is not open"<< 'n';
 }
 std::cin.get();
}
#include <iostream>
#include <fstream>
#include <string>

int main() {
 std::string fileName;
 std::cout << "Enter the file name to be read: ";
 std::cin >> fileName;
 std::ifstream input_file(fileName.c_str());
 std::string line_; // string which text file contents will be stored in
 if(input_file.is_open()){ // validation to see if the file is open
   while(getline(input_file, line_)){
     std::cout<<line_<< 'n'; //prints the contents of the file into the console
   }
  input_file.close();
 }
 else {
   std::cout<<"File is not open"<< 'n';
 }
 std::cin.get();
}

祝你好运。。。

可能是旧编译器不能将字符串作为参数。使用cstring:

ifstream input_file(fileName.c_str());

或者在命令行中指定-std=c++11以获得C++11支持。