I have come across something online about strings. It says to use an array of char
s for a filename input and not string. Why is that?
You seem to be using an older version of C++, where std::ifstream::open
accepts only a const char *
, not a std::string
(see docs):
void open (const char* filename, ios_base::openmode mode = ios_base::in);
As you can see, you cannot pass a std::string
here.
In C++11 and newer, you can pass a std::string
as well:
void open (const string& filename, ios_base::openmode mode = ios_base::in);
A better approach: use std::string
to input the file name and the do File.open(filename.c_str());
to open the file.
That advice is basically wrong. The problem it is attempting to get around is that back in the olden days, file streams took const char*
as the argument for the file name, so you couldn't directly use a std::string
for the name. Of course, the answer to that is to use std::string
, and call c_str()
to pass the file name:
std::string name = "test.txt";
std::ofstream out(name.c_str());
These days, file streams also have a constructor that takes std::string
, so you can do this:
std::string name = "test.txt";
std::ofstream out(name);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With