Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use string or array of char for filename?

I have come across something online about strings. It says to use an array of chars for a filename input and not string. Why is that?

Slide

like image 524
Arvin Wong Avatar asked Feb 08 '23 04:02

Arvin Wong


2 Answers

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.

like image 133
ForceBru Avatar answered Feb 09 '23 20:02

ForceBru


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);
like image 27
Pete Becker Avatar answered Feb 09 '23 18:02

Pete Becker