-4

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
trab
  • 33
  • 5
  • you don't show any prior research, e.g. https://stackoverflow.com/questions/865668/parsing-command-line-arguments-in-c – Marcus Müller Nov 20 '21 at 19:47
  • First step: figure out how to access the command line arguments from within your program. Second step: do something with those arguments (such as treating the first argument as the name of a file). If you haven't done the first step, don't worry about the rest. For now, focus on the task of getting `"X"` when someone invokes your program as `./myprog X`. – JaMiT Nov 20 '21 at 19:57
  • In your favority C++ resource, search for "main parameters" or "main arguments" or "declarations of main function". – Thomas Matthews Nov 20 '21 at 20:00
  • I believe that this topic is always covered in one of the first introductory chapters in every beginner-level C++ textbook, so what textbook are you using, and on which chapter are you on, right now? I'm curious. – Sam Varshavchik Nov 20 '21 at 20:10
  • i'm in algorithms..... its been a rough night lol – trab Nov 20 '21 at 20:26

1 Answers1

0

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.