Reputation: 332
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.
Upvotes: 0
Views: 1414
Reputation: 27528
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
.
Upvotes: 6