0

I want to be able to read text files from the command line. So what I'm trying to do is

1) ./a.out menu1.txt menu2.txt

And let the user choose how many files they want to read from so it could also be

2) ./a.out menu1.txt menu2.txt menu3.txt how do I do that?

menu1.txt 
hamburger 5.00
pizza 3.25
chips 2.50

menu2.txt
hamburger 2.00
pizza 2.35
chips 1.50

menu3.txt
hamburger 4.00
pizza 5.35
chips 0.50

This is what I have so far:

 #include <fstream>
 int main(int argc,  char *argv)
 {
  ifstream inStream; 

  for (int i = 1; i < argc; i++) {

    String menu1 = *argv[i]; 
    String menu2 = *argv[i]; 
    String menu3 = * argv[i]; 
    cout << i << " " << endl;  

}

}

user5999727
  • 21
  • 1
  • 6

2 Answers2

0

Function main provides the number of command line arguments and the argument values (including the name of the program itself): With that, you can achieve what you want.

#include <iostream>

int main( int argc, char* argv[] )
{
    std::cout << "The name used to start the program: " << argv[ 0 ]
    << "\nArguments are:\n";
    for (int n = 1; n < argc; n++)
        std::cout << n << ": " << argv[ n ] << '\n';
    return 0;
}

For more details, confer, for example, cppreference - main function. It explains, for example, that the "name of the program" could be an empty string:

argv[0] is the pointer to the initial character of a null-terminated multibyte strings that represents the name used to invoke the program itself (or an empty string "" if this is not supported by the execution environment)

Stephan Lechner
  • 34,891
  • 4
  • 35
  • 58
0

You've got it mostly done.

  1. You have bad signature of your main - that shold be int main(int argc, char** argv) or int main(int argc, char* argv[])
  2. I don't understand why you try to initialize menu1, menu2 and menu3 with the same argument.

You may store your file paths in some std::vector<std::string> for future use.

#include <string>
#include <vector>

int main(int argc, char** argv)
{
    std::vector<std::string> filePaths;
    for (int i = 1; i < argc; ++i) {
        filePaths.emplace_back(argv[i]);
    }

    //...

    return 0;
}
mpiatek
  • 1,313
  • 15
  • 16