[英]error passing string argument to fstream.open
我正在将MinGW Developer Studio与MinGW编译器一起使用。 我有一个具有以下功能的小程序:
void NameFile()
{
ofstream outfile;
string sFilename = "glatisant.html";
outfile.open(sFilename, ofstream::out);
outfile.close();
}
在构建/编译时,出现以下错误文本:
main.cpp:43:错误:没有匹配函数可调用`std :: basic_ofstreamstd :: char_traits> :: open(std :: string&,const std :: __ Ios_Openmode&)'
fstream:695:注意:候选者为:void std :: basic_ofstream <_CharT,> _Traits> :: open(const char *,std :: _ Ios_Openmode)[with _CharT = char,_Traits => std :: char_traits]
根据fstream.out()的定义,我应该能够传递一个字符串并使其起作用,但事实并非如此。 为什么不?
注意:错误消息似乎表明我的编译器无法识别在c ++ 11中定义的字符串类型参数的可能性。我想我需要让我的环境使用c ++ 11,因为我真的更喜欢使用符合现代标准的方法。
在非C ++ 11中, ofstream::open
需要const char *
,因此尝试传递sFilename.c_str()
:
outfile.open(sFilename.c_str(), ofstream::out);
^^^^^^^^
否则,在C ++ 11中,您也可以传递std::string
,请确保已启用-std=c++11
或-std=c++0x
。
在MingW-Developer-Studio中,您可以转到“项目”>“设置”>“编译”,然后将-std=c++11
或-std=c++0x
放入“其他编译选项”
您可能是说ios_base::out
而不是ofstream::out
。
同样,在C++98/C++03
, ofstream::open
的输入是char const*
,而不是std::string
。
如果您使用的是C++98/C++03
,请更改该行
outfile.open(sFilename, ofstream::out);
至
outfile.open(sFilename.c_str(), ios_base::out);
如果您使用的是C++11
,那么一切都很好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.