getopt不是为一个参数工作

时间:2015-03-16 23:08:34

标签: 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;
    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;
}

一切都很好,除了''选项。由于某种原因,指明一个人不会改变任何东西。它总是返回0.0。我不知道为什么如果其他的args工作得很好的话就会这样。

1 个答案:

答案 0 :(得分:2)

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

#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>

让它适合我。我还将c的类型更改为int(char不会保持-1),然后执行了

memset(&guy, 0, sizeof(guy));

只是为了确保它是一个已知值。编译器警告是你的朋友。我用这个(名为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标识符是最近的,但它是我在builds中使用的旧脚本。