简体   繁体   中英

error passing string argument to fstream.open

I am using MinGW Developer Studio with the MinGW compiler. I have a small program with the following function:

void NameFile()
{
ofstream outfile;
string sFilename = "glatisant.html";
outfile.open(sFilename, ofstream::out);
outfile.close();
}

When building,/compiling, I get the following error text:

main.cpp:43: error: no matching function for call to `std::basic_ofstreamstd::char_traits >::open(std::string&, const std::_Ios_Openmode&)'

fstream:695: note: candidates are: void std::basic_ofstream<_CharT, >_Traits>::open(const char*, std::_Ios_Openmode) [with _CharT = char, _Traits = >std::char_traits]

According to the definition of fstream.out(), I should be able to pass a string and have it work, but it doesn't. Why not?

Note: the error message seems to indicate that my compiler doesn't recognize the possibility of a string-type argument, which is defined in c++ 11. I think I need to get my environment to use c++ 11, because I would really prefer the modern standards-compliant approach.

In non-C++11, method ofstream::open requires const char * , so try to pass sFilename.c_str() :

outfile.open(sFilename.c_str(), ofstream::out);
                      ^^^^^^^^

Otherwise in C++11 you can pass a std::string too, make sure you have enabled -std=c++11 or -std=c++0x .

In MingW-Developer-Studio you can goto Projects > Settings > Compile and put -std=c++11 or -std=c++0x in "Extra compiling options"

在此处输入图片说明

You probably meant ios_base::out instead of ofstream::out .

Also, in C++98/C++03 , the input to ofstream::open is a char const* , not a std::string .

If you are using C++98/C++03 , change the line

outfile.open(sFilename, ofstream::out);

to

outfile.open(sFilename.c_str(), ios_base::out);

If you are using C++11 , all is well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM