C getopt-isn';一个论点不行

C getopt-isn';一个论点不行,c,C,这只是我写的一个简单的程序,目的是练习getopt和structs typedef struct { int age; float body_fat; } personal; typedef struct { const char *name; personal specs; } person; int main(int argc, char *argv[]) { char c; person guy;

这只是我写的一个简单的程序,目的是练习getopt和structs

typedef struct {
        int age;
        float body_fat;
} personal;

typedef struct {
        const char *name;
        personal specs;
} person;


int main(int argc, char *argv[])
{
    char c;
    person guy;
    while((c = getopt(argc, argv, "n:a:b:")) != -1)
        switch(c) {
        case 'n':
            guy.name = optarg;
            break;
        case 'a':
            guy.specs.age = atoi(optarg);
            break;
        case 'b':
            guy.specs.body_fat = atof(optarg);
            break;
        case '?':
            if(optopt == 'a') {
                printf("Missing age!\n");
            } else if (optopt == 'b') {
                printf("Missing body fat!\n");
            } else if (optopt == 'n') {
                printf("Missing name!\n");
            } else {
                printf("Incorrect arg!\n");
            }
            break;
        default:
            return 0;
        }

    printf("Name: %s\nAge: %i\nFat Percentage: %2.2f\n",
        guy.name, guy.specs.age, guy.specs.body_fat);
    return 0;
}

除了“b”选项外,其他一切都正常。出于某种原因,指定一个人不会改变任何事情。它始终返回为0.0。我不明白如果其他参数工作正常,为什么会出现这种情况。

您的示例缺少声明相应原型的头文件。添加这些

#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
只是为了确保它是一个已知的值。编译器警告是您的朋友。我使用此脚本(名为
gcc normal
)应用警告:

#!/bin/sh
# $Id: gcc-normal,v 1.4 2014/03/01 12:44:54 tom Exp $
# these are my normal development-options
OPTS="-Wall -Wstrict-prototypes -Wmissing-prototypes -Wshadow -Wconversion"
${ACTUAL_GCC:-gcc} $OPTS "$@"

虽然RCS标识符是最近才出现的,但它是我在中使用的一个旧脚本。

您包括哪些标题?我包括并感谢您。有一次,我把所有的东西都包括进去了,但没有修改代码。我的代码的哪一部分特别需要这个头?我习惯于只为exit()添加它,而您的程序不使用它(习惯)。我通过打开编译器警告(另一个习惯)注意到了char/c。实际上,我在stdlib.h之后添加了unistd.h,因为我编译的系统没有通过stdlib.h声明getopt。对于
atof()
,必须包含它。否则它将使用返回类型
int
隐式声明,而不是
double
(这就是它不能正常工作的原因)。启用警告的另一个原因是有意义的。我也不知道你需要stdlib.h退出。我想我以前从未在C中使用过exit。非常感谢!
#!/bin/sh
# $Id: gcc-normal,v 1.4 2014/03/01 12:44:54 tom Exp $
# these are my normal development-options
OPTS="-Wall -Wstrict-prototypes -Wmissing-prototypes -Wshadow -Wconversion"
${ACTUAL_GCC:-gcc} $OPTS "$@"