user1215882
user1215882

Reputation: 5

How to check for command line parameters on C++ in UNIX?

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

Answers (4)

Meysam
Meysam

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

ahj
ahj

Reputation: 795

Highly recommend boost program_option library for command line parsing.

Upvotes: 0

David Schwartz
David Schwartz

Reputation: 182753

if (argc<2)
{
    fprintf(stderr, "This program requires more parameters\n");
    return -1;
}

Upvotes: 3

user647772
user647772

Reputation:

Use getopt.

Upvotes: 0

Related Questions