[英]ofstream returning error “No matching function to call std::basic_ofstream<char>::close(const char [14])”
Need help fixing my code, not sure what's wrong. 需要帮助修复我的代码,不确定出什么问题。 I'm using C++11, trying to write a vector to a file by individually writing each struct.
我正在使用C ++ 11,试图通过分别编写每个结构将矢量写入文件。 The section of code returning an error is:
返回错误的代码部分是:
string craigSave = "craigSave.txt";
ofstream file(craigSave.c_str());
file.open("craigSave.txt");
for (int i=0; i<finalVector.size(); i++){
file << finalVector[i]<<endl;
}
file.close("craigSave.txt");
cout<<"Thanks for shopping!"<<endl;
done = true;
The error returned is on the "file.close" line and is: 返回的错误在“ file.close”行上,并且是:
error: no matching function for call to 'std::basic_ofstream::close(const char [14])'
错误:没有匹配的函数调用'std :: basic_ofstream :: close(const char [14])'
I research on this error seems to point to needing to use char* as an argument instead of a string, but I'm using C++11, so it should accept strings. 我研究此错误似乎指向需要使用char *作为参数而不是字符串,但是我使用的是C ++ 11,因此它应该接受字符串。 Also it is strange that there is no error for the file.open line, as all research shows the error being there, not at file.close
同样奇怪的是,file.open行没有错误,因为所有研究都表明错误存在于此,而不是file.close
Just use file.close();
只需使用
file.close();
, there's no need to pass the file name again. ,则无需再次传递文件名。
See http://www.cplusplus.com/reference/fstream/ofstream/close/ . 参见http://www.cplusplus.com/reference/fstream/ofstream/close/ 。
Also, ofstream
s are RAII objects, which means that the file will automatically be closed once the ofstream
object goes out of scope (see do I need to close a std::fstream? ): 另外,
ofstream
是RAII对象,这意味着一旦ofstream
对象超出范围,文件将自动关闭(请参阅是否需要关闭std :: fstream? ):
{
ofstream out("name");
// do something with out...
} // out.close is called automatically
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.