开发者

How to automatically open an input file in C++?

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 inpu开发者_如何学Got 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".


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


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜