Reputation: 5
How could you error check for command line parameters on C++ in UNIX? For example, if you entered no parameters, how would you print out an error message rather than just getting a segmentation fault?
Upvotes: 0
Views: 1010
Reputation: 18127
If argc
is not greater than 1, then user has provided no command line parameters:
#include <stdio.h>
int main (int argc, char *argv[])
{
if (argc < 2)
{
printf("The command had no arguments.\n");
}
return 0;
}
Upvotes: 1
Reputation: 795
Highly recommend boost program_option
library for command line parsing.
Upvotes: 0
Reputation: 182753
if (argc<2)
{
fprintf(stderr, "This program requires more parameters\n");
return -1;
}
Upvotes: 3