trungnt trungnt - 1 year ago 69
C Question

How do you pass an optional command line argument for C/C++?

I'm trying to write a program that will count the number of different possible passwords using the digits 0 - 9 under certain constraints. It's to have one required command line argument, which will be the number of digits in the password, while also having an optional argument, which will be the prohibited digit. No argument inputted will mean that all digits are allowed.

For example, should my program be called combinations:

$ combinations 8 3 #find number of passwords of length 8 with '3' not allowed

I tried looking it up and found that you can make an argument optional to a function with

int myfunction( int optional = 3);

for example. However that seems to set the value to a default value should nothing is input. I need it to allow all digits if it's left blank. How would I do it for command line arguments as well?

Answer Source

Command line arguments are passed from the command line into your program as parameters to your main function. The signature of which needs to be int main(int argc, char** argv).

The second parameter is an array of null terminated strings which hold every argument passed in the invocation of the program (including the name of the program). The first is is how many strings are in the array.

You will need to check that argc > 2 and then parse argv[2] for the digit.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download