I have a program that does two separate things. But I want to the program to only run one specific part based on what I enter in the command like in the format
program -a
program -s
where the a or s would be programmed to tell it to do something specific.
For example, if my program was something like:
# program -a entered
z = x + y
# program -s entered
z = x - y
Now I could easily do this with an if statement after running the program, but is it possible to directly skip to a statement like I said from the command prompt?
int main(int argc, char* argv[]) {
if (argc >= 2) {
if (strcmp(argv[1], "-a") == 0) {
z = x + y;
} else if (strcmp(argv[1], "-s") == 0) {
z = x - y;
}
}
return 0;
}
Determine if the value of argv[1]
equal to "-a"
or "-s"
You can use a switch
statement on command-line arguments (in this case argv[1]
).argv[1]
is a string containing the options you have given ("-a", "-s" etc).
But you have to perform certain checks for the validity of the command-line arguments before you can use them like this.
argc == 2
strlen(argv[1]) == 2
argv[1][0] == '-'
An MCVE would look like this:
#include <stdio.h>
#include <string.h>
int main(int argc, char* argv[]) {
if(argc == 2 && strlen(argv[1]) == 2 && argv[1][0] == '-')
{
switch(argv[1][1])
{
case 'a':
//do something
break;
case 's':
//do something else
break;
default:
//do the default thing
break;
}
}
else
{
//print appropriate error message
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With