用于在C++中将信息写入文件的函数

Jac*_*ses 0 c++ fstream ofstream c++11

我一直在为学校做项目,我遇到了一个问题.我试图避免在程序中对所有内容进行硬编码,而我的部分要求是使用fstream.这是抛出错误的原因.我使用G ++作为我的编译器.

void order::printToFile(string file)
{
ofstream output;

try
{
    output.open(file, ios::app);
}

catch(...)
{
    cerr << "An error has occurred";
}

output << this->info.orderID << setw(10) << this->info.type << setw(10) << this->info.quantity << setw(10) << this->info.zip << setw(10) << (this->info.shipCost + this->info.wholesale) << setw(10) << this->info.profit << endl << endl;

output.close();

}
Run Code Online (Sandbox Code Playgroud)

它给了我以下错误:

没有匹配的功能要求 'std::basic ofstream<char>::open( std::string&, const openmode&)'

有人可以帮我一把吗?谢谢

0x4*_*2D2 5

没有匹配的功能要求 'std::basic ofstream<char>::open( std::string&, const openmode&)'

"无匹配函数"错误意味着编译器搜索但找不到与调用站点提供的参数匹配的重载.open()在C++ 11之前有一个带有类型缓冲区的重载char const*.这已经更新,除了第一个重载之外,open()现在支持类型的参数std::string const&.

问题必须是您的编译器不能识别C++ 11.添加-std=c++11到命令行应该可以解决问题.另一方面,如果你不能这样做,你总是可以使用c_str()以下方法获取指向缓​​冲区的指针:

output.open(file.c_str(), ios::app);
//              ^^^^^^^^
Run Code Online (Sandbox Code Playgroud)

您应该知道的另一件事是IOStreams默认设计为不抛出异常.相反,它们以称为"流状态"的位掩码类型的形式反映流错误.可以使用布尔运算符方法流支持来访问它.

您可以通过设置exceptions()掩码中的相应位来启用异常,但我不建议将其用于这样一个简单的示例.只需在打开后检查流就足够了:

if (std::ofstream output(file.c_str(), std::ios_base::app)) {
    output << "...";
}
else {
    std::cerr << "An error has occurred.";
}
Run Code Online (Sandbox Code Playgroud)

最后,流不需要手动关闭.当它们被定义的范围结束它们的析构函数时,将调用它自动释放文件资源.close()只有在您希望查看它是否有效,或者您不再需要该文件并希望立即刷新输出的情况下,才需要进行调用.