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
CodePudding user response:
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.