2

In my program written in C++, I open a file as follows:

std::ifstream file("testfile.txt");

This usage can handle the scenario where the input file has a fixed name of "testfile.txt". I would like to know how to allow the user to input a file name, e.g., "userA.txt", and the program automatically opens this file, "userA.txt".

user297850
  • 7,705
  • 17
  • 54
  • 76

2 Answers2

7

Use a variable. I suggest finding a good introductory book if you're not clear on what they are yet.

#include <iostream>
#include <string>

// ...

std::string filename;    // This is a variable of type std::string which holds a series of characters in memory

std::cin >> filename;    // Read in the filename from the console

std::ifstream file(filename.c_str());    // c_str() gets a C-style representation of the string (which is what the std::ifstream constructor is expecting)

If the filename can have spaces in it, then cin >> (which stops input at the first space as well as newline) won't cut it. Instead, you can use getline():

getline(cin, filename);    // Reads a line of input from the console into the filename variable
Community
  • 1
  • 1
Cameron
  • 96,106
  • 25
  • 196
  • 225
3

You can obtain command line arguments with argc and argv.

#include <fstream>

int main(int argc, char* argv[])
{
    // argv[0] is the path to your executable.
    if(argc < 2) return 0 ;

    // argv[1] is the first command line option.
    std::ifstream file(argv[1]);

    // You can process file here.
}

The command line usage will be:

./yourexecutable inputfile.txt
Tugrul Ates
  • 9,451
  • 2
  • 33
  • 59