简体   繁体   中英

How to read command line arguments from a text file?

I have a program that takes in one integer and two strings from a text file "./myprog < text.txt" but I want it to be able to do this using command line arguments without the "<", like "./myprog text.txt" where the text file has 3 input values.

3 <- integer
AAAAAA <- string1  
AAAAAA <- string2

If the reading of the parameters must be done solely from the file having it's name, the idiomatic way is, I would say, to use getline() .

std::ifstream ifs("text.txt");
if (!ifs)
    std::cerr << "couldn't open text.txt for reading\n";
std::string line;
std::getline(ifs, line);
int integer = std::stoi(line);
std::getline(ifs, line);
std::string string1 = line;
std::getline(ifs, line);
std::string string2 = line;

Because there are little lines in your file, we can allow ourselves some repetition. But as it becomes larger, you might need to read them into a vector:

std::vector<std::string> arguments;
std::string line;
while (getline(ifs, line))
    arguments.push_back(line);

There some optimizations possible, as reusing the line buffer in the first example and using std::move() , but they are omitted for clarity.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM