Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

does ifstream accept variable file name?

Tags:

c++

does ifstream accept variable file name? I am trying to give a fine as an argument and then will try to read it. What should be the best way?

like image 391
Coka Avatar asked Feb 09 '26 16:02

Coka


2 Answers

Yes, of course it does.

const char * filename = "abc.txt";

std::ifstream fin(filename);

Or using std::string

std::string filename = "abc.txt";

std::ifstream fin(filename.c_str());

With C++11, you can just use the string directly.

std::ifstream fin(filename);
like image 188
Benjamin Lindley Avatar answered Feb 13 '26 07:02

Benjamin Lindley


You can also use a character array (which is basically what a string is anyway):

char filename[20];

std::cout << "Enter the filename (no more than 20 characters): ";
std::cin >> filename;

std::ifstream inputFile( filename );

That should work and allow you to take dynamic user input for your filename.

like image 39
Richard D Avatar answered Feb 13 '26 06:02

Richard D