how to validate a string variable for multiple combinations of comma separated values received from command line for getopt?
case 'a' :
flaga=1;
alg = optarg;
printf("you entered option -a \"%s\"\n", optarg);
if(strcmp(alg,"lr") == 0 )
{
....//valid
}
else if(strcmp(alg,"lda") == 0 )
{
....//valid
}
else if(strcmp(alg,"knn") == 0 )
{
...//valid
}
"""""
""""
else
{
printf("wrong value entered for option -a \n");
exit();
}
option -a can accept these values : "knn","lda","lr","kart","nb","svm" .
The above code handles errors perfectly if user passes only single value .
But option -a can accept multiple values as comma separated ,
Eg : -a knn,lr,lda
User can pass these values in any combination of any values !!
Eg : -a knn,lr,lda
Eg : -a knn,lda.lr
Eg : -a lda,lr
How to Check if user has passed valid values for option -a ?
The above code i have written is included in switch case and can handle if only single value for option -a is passed .
When you allow several options that are separated with a comma, you must split the string at the commas and process every token. One way to split strings is the library funtion
strtok
from<string.h>
. Take care to remove whitespace from the tokens when you compare them.Another question is how you want to represent the result. One way is to fill an initially zeroes out array of options with ones as appropriate. Another way is to use a bit-combination so that options 0,1 and 3 correspond to 2⁰ + 2¹ + 2³ = 1 + 2 + 8 = 11. That's the method I used below.
The example program below provides a function
multi_opt
that parses a list of options that are separated by commas. When an unknown option is dound, the program exits immediately. You may opt to return an invalid bit cobination instead and pass the responsibility of error handling to the calling code.The function also works when the argument string is empty, in which case no options are set. The
main
function shows how to use that function..You can try with the
strtok()
function:PS:
strtok()
is part ofstring.h
EDIT: I don't think this code will have your desired behaviour. This will be better:
This printf o/p :1. you entered option -a "svm,lr"
This printf o/p :2. you entered option -a "svm" But expected : svm,lr