1

I'm trying to get the following code to work with the command

rectangle –area –length 12 –breadth 34

But I get the error

rectangle: invalid option -- r

using the short argument option

rectangle -a -l 12 -b 34

I get the right answer

Area: 408

The code:

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

/** Program to calculate the area and perimeter of 
 * a rectangle using command line arguments
 */
void print_usage() {
    printf("Usage: rectangle [ap] -l num -b num\n");
}

int main(int argc, char *argv[]) {
    int opt= 0;
    int area = -1, perimeter = -1, breadth = -1, length =-1;

    //Specifying the expected options
    //The two options l and b expect numbers as argument
    static struct option long_options[] = {
        {"area",      no_argument,       0,  'a' },
        {"perimeter", no_argument,       0,  'p' },
        {"length",    required_argument, 0,  'l' },
        {"breadth",   required_argument, 0,  'b' },
        {0,           0,                 0,  0   }
    };

    int long_index =0;
    while ((opt = getopt_long(argc, argv,"apl:b:", 
                   long_options, &long_index )) != -1) {
        switch (opt) {
             case 'a' : area = 0;
                 break;
             case 'p' : perimeter = 0;
                 break;
             case 'l' : length = atoi(optarg); 
                 break;
             case 'b' : breadth = atoi(optarg);
                 break;
             default: print_usage(); 
                 exit(EXIT_FAILURE);
        }
    }
    if (length == -1 || breadth ==-1) {
        print_usage();
        exit(EXIT_FAILURE);
    }

    // Calculate the area
    if (area == 0) {
        area = length * breadth;
        printf("Area: %d\n",area);
    }

    // Calculate the perimeter
    if (perimeter == 0) {
        perimeter = 2 * (length + breadth);
        printf("Perimeter: %d\n",perimeter);
    }
    return 0;
}
alk
  • 69,737
  • 10
  • 105
  • 255
pandoragami
  • 5,387
  • 15
  • 68
  • 116

1 Answers1

2

Long options have to be prefixed with a -- not a single -.

So

rectangle –-area –-length 12 –-breadth 34

should work.

Update

Alternativly the following form can be used:

rectangle –-area –-length=12 –-breadth=34

You might like to correct the usage statement by changing:

printf("Usage: rectangle [ap] -l num -b num\n");

to

printf("Usage: rectangle [-a|--area -p|--perimeter] -l|--length num -b|--breadth num\n");
alk
  • 69,737
  • 10
  • 105
  • 255
  • I get `Usage: rectangle [ap] -l num -b num` – pandoragami Apr 07 '14 at 12:00
  • I tried `rectangle --area --length 12 --breadth 34` and got `Usage: rectangle [-a|--area -p|--perimeter] -l|--length num -b|--breadth num` – pandoragami Apr 07 '14 at 23:50
  • I tried your update as `rectangle --area --length=12 --breadth=34` and I still got `Usage: rectangle [-a|--area -p|--perimeter] -l|--length num -b|--breadth num` – pandoragami Apr 10 '14 at 01:23