没有匹配的函数调用`std::basic_ofstream<char, std::char_traits<char> >::basic_ofstream(std::string&)'。

9

我正在尝试编写一个程序,要求用户输入文件名,然后打开该文件。当我编译它时,我收到以下错误提示:

no matching function for call to std::basic_ofstream<char, 
std::char_traits<char> >::basic_ofstream(std::string&)

这是我的代码:
using namespace std;

int main()
{ 
    string asegurado;
    cout << "Nombre a agregar: ";
    cin >> asegurado;

    ofstream entrada(asegurado,"");
    if (entrada.fail())
    {
        cout << "El archivo no se creo correctamente" << endl;
    }
}      
2个回答

19

std::ofstream只有在使用C++11或更高版本时才能使用std::string进行构造。通常情况下,可以通过使用-std=c++11(gcc,clang)来实现。如果您无法访问c++11,则可以使用std::stringc_str()函数将const char *传递给ofstream构造函数。

此外,正如Ben指出的,您正在使用空字符串作为构造函数的第二个参数。如果提供第二个参数,则需要是ios_base::openmode类型。

通过这些修改,您的代码应该是:

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

或者

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

我建议您阅读:为什么“using namespace std;”被认为是不良实践?


我认为情况并非如此。它在c++14中仍然失败http://ideone.com/PVylpo,问题在于没有构造函数接受字符串字面值作为第二个参数。 - Fantastic Mr Fox
非常感谢!但是在代码中c_str()函数会在哪里?我以前从未使用过它。 - ToM MaC
@ben 这就是我回答的原因。我也指出了你的错别字,并标注了你的名字。 - NathanOliver
好的,回答了所有情况+1。 - Fantastic Mr Fox
我做到了,我只是在ofstream entrada(asegurado);函数中添加了c_str()函数,现在它可以正常工作了。接下来我会阅读一下为什么使用"using namespace std;"被认为是不好的习惯。非常感谢你的帮助!祝贺你! - ToM MaC

1
你的构造函数 ofstream entrada(asegurado,"");std::ofstream 不匹配。第二个参数需要是 ios_base,请参见下文:
entrada ("example.bin", ios::out | ios::app | ios::binary);
                            //^ These are ios_base arguments for opening in a specific mode.

为了使您的程序运行,您只需要从ofstream构造函数中删除字符串文字:
ofstream entrada(asegurado);

请点击此处查看实时示例。

如果您正在使用c++03或更低版本,则无法将std::string传递给ofstream的构造函数,您需要传递一个c字符串:

ofstream entrada(asegurado.c_str());

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接