0

If I set a string as a filename, it doesn't work and I have no idea why. (I'm using codeblocks and it seems to work on other IDEs)

#include <iostream>
#include <fstream>
using namespace std;
int main()
{
   string FileName="Test.txt";
   ofstream File;
   File.open(FileName);
}

This does not work,while this next one does:

#include <iostream>
#include <fstream>
using namespace std;
int main()
{
   ofstream File;
   File.open("Test.txt");
}

Error message:

no matching function for call to std::basic_ofstream::open(std::string&)

Can someone help a bit with this problem, I cannot understand why this error occurs.

Murmel
  • 5,402
  • 47
  • 53
CasualCoder
  • 332
  • 4
  • 6
  • 4
    Do you use the compiler switch -std=c++11? –  Jan 16 '18 at 15:13
  • Do you have a pre-C++03 compiler? – molbdnilo Jan 16 '18 at 15:14
  • 4
    Confusion between C strings and C++ strings, try File.open(FileName.c_str());. Or use a more up to date compiler. – john Jan 16 '18 at 15:15
  • @molbdnilo the std::string overload is C++11, not C++03. –  Jan 16 '18 at 15:16
  • 1
    https://stackoverflow.com/questions/18174988/how-can-i-add-c11-support-to-codeblocks-compiler – drescherjm Jan 16 '18 at 15:16
  • You probably don't have `c++11` so you cannot use `const std::string &` overload http://en.cppreference.com/w/cpp/io/basic_ifstream/open – Killzone Kid Jan 16 '18 at 15:23
  • 1
    This doesn't address the question, but `ofstream File; File.open(FileName);` should be `ofstream File(FileName);`. There's no reason here for creating an empty file object and then opening it. – Pete Becker Jan 16 '18 at 16:05

1 Answers1

6

Due to what should be considered a historical accident in the early era of C++ standardisation, C++ file streams originally didn't support std::string for filename parameters, only char pointers.

That's why something like File.open(FileName), with FileName being a std::string, didn't work and had to written as File.open(FileName.c_str()).

File.open("Test.txt") always worked because of the usual array conversion rules which allow the "Test.txt" array to be treated like a pointer to its first element.

C++11 fixed the File.open(FileName) problem by adding std::string overloads.

If your compiler doesn't support C++11, then perhaps you should get a newer one. Or perhaps it does support C++11 and you just have to turn on the support with a flag like -std=c++11.

Christian Hackl
  • 27,051
  • 3
  • 32
  • 62