C++ Error no matching function for call to 'std::basic_ofstream::basic_ofstream(std::string&)

Table of Contents

问题 

解释:

解决方法:


问题 

string filename = "1.txt";  
ifstream fin;  
fin.open(filename);  

上述语句会产生如下错误:

error: no matching function for call to 'std::basic_ifstream::basic_ofstream(std::string&)

解释:

std::ofstream can only be constructed with a std::string if you have C++11 or higher. Typically that is done with -std=c++11 (gcc, clang). If you do not have access to c++11 then you can use the c_str() function of std::string to pass a const char * to the ofstream constructor.

Also as Ben has pointed out you are using an empty string for the second parameter to the constructor. The second parameter if proivided needs to be of the type ios_base::openmode.

With all this your code should be

ofstream entrada(asegurado); // C++11 or higher

or

ofstream entrada(asegurado.c_str());  // C++03 or below

原文地址:地址

解决方法:

也就是我这里使用的C++编译版本比较低,这里解决方式可以使用.c_str()方法。

string filename = "1.txt";  
ifstream fin;  
fin.open(filename.c_str());  

当然,也有第二种解决方式,比较low一点:

cout<<"输入文件名及路径以创建该文件,如:E:/a.txt"<>fileName;
ofstream fout(fileName);

 


作者:无涯明月

上篇: C++ sort函数


 

 

你可能感兴趣的:(C++)