Problem : File opening with a variable containing a string

Hello everybody,


This code works :

ofstream result("jonathan.txt");

Why not this one ?

1
2
3
4
5
   string name = "jonathan";
   string resultFile = name;
   resultFile.append(".txt");
   cout << resultFile << endl;
   ofstream result(resultFile); //line 15 



The error is :

C:\Users\**\Desktop\projects\2.1\main.cpp|15|error: no matching function for call to 'std::basic_ofstream<char, std::char_traits<char> >::basic_ofstream(std::string&)'|


Knowing that :

resultFile == "jonathan.txt" IS TRUE

- Why doesn't it work ?
- What is the shortest solution to make it work ?


Have a good day :-)
ofstream result(resultFile.c_str());
Thanks, works like a charm :-)

I still don't quite understand by the way why is the function accepting c-strings only.
I always thought it was weird too. They could have easily added an overload to accept std::strings.
or
1
2
3
std::string::operator const char* const() const{
  return this->c_str();
}

Edit: const correct
Last edited on
casting operators are error prone, though. But yeah they could've done any number of things.
Topic archived. No new replies allowed.