开发者

C switch question

I'm new to programming and I would like to add to a switch that would take in option cases such as -aa, -aaa, -aaaaaa etc where each of these three cases could serve a singular function in addition to case a?

I was thinking...

    int option = getopt (argc, argv, "abcd");
    switc开发者_运维百科h(option){
    case 'a': BLAH = TRUE;
              break;
    case 'b': FOO = TRUE;
              break;
    case 'c': BAR = TRUE;
              break;
    case 'd': BAZ = TRUE;
              break;
    }
    for(int i = 1; i<argc; i++){
    if ( argv[i][0] == '-' && argv[i][1] == 'a' && argv[i][i+2] == 'a' )
       myOption =TRUE;
    }

But would this work? Thanks for reading.


The getopt_long(3) function provides command-line parsing to many programs, typically with invocations like this:

struct option long_options[] = {
    {"add",         0, 0, 'a'},
    {"binary",      0, 0, 'B'},
    {"base",        1, 0, 'b'},
...
    {"Optimize",        1, 0, 'O'},
    {"preprocess",      0, 0, 'p'},
    {NULL, 0, 0, 0},
};


while ((c = getopt_long(argc, argv, "adf:h::rRVvI:b:BCD:NSm:qQn:XKTWkO:po:", long_options, &o)) != -1)
{
    switch (c) {
    case 0:
        PERROR("Assert, in getopt_long handling\n");
        display_usage(progname);
        exit(0);
        break;
    case 'a':
        count++;
        option = OPTION_ADD;
        break;
    case 'd':
        debug++;
        skip_read_cache = 1;
        break;
/* ... and so forth */

You might be able to use getopt_long(3) to scan an array of inputs to look for multiple inputs (think add, binary, etc. from the long_options[]) that map to a single short option (a or B).

But if you are more specific about what you're trying to accomplish, there might be a better mechanism available.


No, this probably would not work. The best way in C (assuming you use Linux) is to use some of the getopt functions that the GNU C library provides. You could also use if..else if and strcmp() if you just need to process one or two long options.

Last time I checked similar features exist for BSD's libc as well (might be a bit different, though).


'aaa' is not integer, not char, and, not any type in the C language. The expression passed to switch statement should return an integer. So, switch statement is going to complain there.

For non integer comparisons such as the ones you have listed out, using if-else should be good.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜