Reputation: 93
I have a program that requires a command line argument to run properly, but it runs even when no argument is provided. How do I ensure that an argument is provided before it runs?
int main(int argc, const char ** argv) {
std::ifstream b(argv[1]);
Word c;
c.fillWords(c.getWordsAdress(), &b);
c.printWord(c.getWordsAdress());
}
Upvotes: 0
Views: 81
Reputation: 14659
You can just check the argument count and if it is less than 2, that means that no arguments were provided. The argument count will always have at least 1, which contains the name of the program.
int main(int argc, char** argv)
{
if(argc < 2) {
cerr << "usage: " << argv[0] << " -argument";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
Upvotes: 0
Reputation: 6349
Check the argument count like this:
int main( int argc, const char* argv[] )
{
if (argc < 2)
return 1;
// your code here
}
Upvotes: 1