I have this little piece of C code, which takes a set of command-line arguments --help
, -h
, -d
and -o
(each correspondingly representing "Help", "Hexadecimal", "Decimal", "Octal"), and I am calling certain functions depending in which argument is passed, -h
will call hexaFlag()
, -dh
will call hexaFlag()
and decFlag()
. However, in order to do this, I am employing a block of if else
that is messy. Is there any less convoluted way to achieve this? I was told to use a switch
statement, but I do not know how I could use it here considering I am checking for different conditions each time.
main()
function of the code I am referring to:
int main(int argc, char* argv[]){
if(argc == 1){
printf("%s",usage());
printf("Use --help for more options.\n");
}
else if(strcmp(argv[1], "--help") == 0){
printf("%s", usage());
printf("Options are:\n -h = Hexadecimal values\n -d = Decimal values\n -o = Octal values\n --help = Shows this message\n");
}
else if(strchr(argv[1], '-') != NULL){
if(strchr(argv[1], 'h') != NULL){
hexaFlag(argc, argv);
}
if(strchr(argv[1], 'd') != NULL){
decFlag(2, argc, argv);
}
if(strchr(argv[1], 'o') != NULL){
octaFlag(argc, argv);
}
}
else {
decFlag(1, argc, argv);
}
return 0;
}
Aucun commentaire:
Enregistrer un commentaire