getopt 无效选项命令行 C

getopt invalid option command line C

在命令行上 运行 salary -b -r 4 -t 10 75000 后,我收到以下错误,但不确定原因。我收到无效选项的确切原因是什么?解决方案是什么?

薪水:无效选项 -- 'r'

薪水:无效选项 -- 't'

薪水:缺少税金。

用法:薪水[-bv] [r rnum] -t tnum base

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int debug = 0;


int main(int argc, char **argv)
{
    extern char *optarg;
    extern int optind;
    int c, err = 0; 
    int tflag=0; 
    double baseSalary,bonus1,bonus2,percentRaise,taxes,finalSalary = 0; 
    
    static char usage[] = "usage: %s [-bv] [r rnum] -t tnum base\n";

    while ((c = getopt(argc, argv, "bc:d:")) != -1)
        switch (c) {
        case 'd':
            debug = 1;
            break;
        case 'b':
            bonus1=5000;
            break;
        case 'v':
            bonus2=6000;
            break;
        case 'r':
            percentRaise = atoi(optarg);
            if ((percentRaise<2) || (percentRaise>10)){
                fprintf(stderr, "%s:Out of bound raise percent.\n", argv[0]);
                exit(1);
            }
            percentRaise/=10;
            percentRaise+=1;
            break;
        case 't':
            taxes = atoi(optarg);
            if ((taxes<5)||(taxes)>30){
                fprintf(stderr, "%s:Out of bound tax percent.\n", argv[0]);
                exit(1);
            }
            taxes /=10;
            taxes = 1-taxes;
            tflag = 1;
            break;
        case '?':
            err = 1;
            break;
        }
    if (tflag == 0) {   /* -c was mandatory */
        fprintf("Result: Missing taxes.\n");
        fprintf(stderr, usage, argv[0]);
        exit(1);
    }  
            
    if (optind < argc){ /* these are the arguments after the command-line options */
        baseSalary = atoi(argv[optind]);
        if ((baseSalary>90000) || (baseSalary<20000)){
            fprintf(stderr, "%s:Out of bound salary\n", argv[0]);
            fprintf(stderr, usage, argv[0]);
            exit(1);
        }
    }
    finalSalary += baseSalary;
    finalSalary+=bonus2;
    finalSalary*=percentRaise;
    finalSalary+=bonus1;
    finalSalary*=taxes;

    printf("Result: %.2f\n", finalSalary);
    exit(0);
}

您的选项字符串与您期望的选项不匹配。

选项字符串中的字母后跟 : 指定带参数的选项,而后跟 : 的字母表示不带参数的选项参数。

这意味着您的选项字符串 "bc:d:" 需要一个不带参数的 b 选项,一个带参数的 c 选项,以及一个带参数的 d 选项.那不符合你的用法。你反而想要:

"bdvr:t:"