c - getopt isn't working for one argument -


this simple program wrote in order practice 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; } 

everything works fine except 'b' option. reason specifying 1 doesn't change anything. returns 0.0. don't why if other args work fine.

your example missing header files declare corresponding prototypes. adding these

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

makes work me. changed type c int (a char not hold -1), , did a

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

just ensure known value. compiler warnings friend. used (a script named gcc-normal) apply warnings:

#!/bin/sh # $id: gcc-normal,v 1.4 2014/03/01 12:44:54 tom exp $ # these normal development-options opts="-wall -wstrict-prototypes -wmissing-prototypes -wshadow -wconversion" ${actual_gcc:-gcc} $opts "$@" 

though rcs-identifier recent, old script use in builds.


Comments

Popular posts from this blog

node.js - Mongoose: Cast to ObjectId failed for value on newly created object after setting the value -

gradle error "Cannot convert the provided notation to a File or URI" -

python - NameError: name 'subprocess' is not defined -