beauxq
beauxq

Reputation: 1286

why this compiler error? - no matching function for call to 'std::basic_ofstream<char>::open(std::string&)'

This works on Visual Studio and it works on GCC 4.9.2 on one computer.

But on a different computer, I think it's the same GCC 4.9.2 compiler, but it gives me this error.

Am I missing something? What's going on?

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()
{
    string filename;
    filename = "teststring";
    ofstream fout;
    fout.open(filename);
    fout << "Hello world!" << endl;
    fout.close();
    return 0;
}

.

||=== Build: Debug in fileiotest (compiler: TDM32 GNU GCC Compiler 4.9.2 dw2) ===|
F:\Users\XXX\cpp\fileiotest\main.cpp||In function 'int main()':|
F:\Users\XXX\cpp\fileiotest\main.cpp|12|error: no matching function for call to 'std::basic_ofstream<char>::open(std::string&)'|
F:\Users\XXX\cpp\fileiotest\main.cpp|12|note: candidate is:|
F:\TDM-GCC-32\lib\gcc\mingw32\4.9.2-dw2\include\c++\fstream|716|note: void std::basic_ofstream<_CharT, _Traits>::open(const char*, std::ios_base::openmode) [with _CharT = char; _Traits = std::char_traits<char>; std::ios_base::openmode = std::_Ios_Openmode]|
F:\TDM-GCC-32\lib\gcc\mingw32\4.9.2-dw2\include\c++\fstream|716|note:   no known conversion for argument 1 from 'std::string {aka std::basic_string<char>}' to 'const char*'|
||=== Build failed: 1 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|

Upvotes: 6

Views: 25450

Answers (1)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385295

This overload's new in C++11, which means you need to pass -std=c++11 in the build command.

In C++03, we used to write this:

fout.open(filename.c_str());

Upvotes: 14

Related Questions