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?
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);
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.
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