Problem : File opening with a variable containing a string
Dec 7, 2010 at 10:14pm UTC
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 :-)
Dec 7, 2010 at 10:24pm UTC
ofstream result(resultFile.c_str() );
Dec 8, 2010 at 12:01am UTC
Thanks, works like a charm :-)
I still don't quite understand by the way why is the function accepting c-strings only.
Dec 8, 2010 at 12:06am UTC
I always thought it was weird too. They could have easily added an overload to accept std::strings.
Dec 8, 2010 at 12:41am UTC
or
1 2 3
std::string::operator const char * const () const {
return this ->c_str();
}
Edit: const correct
Last edited on Dec 8, 2010 at 12:45am UTC
Dec 8, 2010 at 1:58am UTC
casting operators are error prone, though. But yeah they could've done any number of things.
Topic archived. No new replies allowed.