C及C++编译时候出现的一些问题与解决方案
字符串问题
[no matching function for call to ‘std::basic_ofstream >::basic_ofstream(std::string&)’]
编译时候报错为no matching function for call to std::basic_ofstream<char, std::char_traits>::basic_ofstream(std::string&) 原因是C++的string类与C的字符串存在不同,一些函数无法将string类作为参数使用。
std::ofstream
can only be constructed with astd::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 thec_str()
function ofstd::string
to pass aconst char *
to theofstream
constructor.解决方案:转换为C的字符串
1.
1
2
3
4char filename[10];
strcpy(filename, "1.txt");
ifstream fin;
fin.open(filename);2.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16using namespace std;
int main()
{
string asegurado;
cout << "Nombre a agregar: ";
cin >> asegurado;
ofstream entrada(asegurado,"");/*编译报错*/
//ofstream entrada(asegurado); // C++11 or higher
//ofstream entrada(asegurado.c_str()); // C++03 or below
if (entrada.fail())
{
cout << "El archivo no se creo correctamente" << endl;
}
}