c - getopt not working correctly when run from unix command line -


i wrote (copied , pasted google , simplified) c program use getopt print out values of arguments passed in unix command line.

from unix command line:

./myprog -a 0 -b 1 -c 2 

my c code is:

#include <stdio.h> #include <stdlib.h> #include <unistd.h>  int main(int argc, char *argv[]) {     int i;      while ((i = getopt(argc, argv, "abc")) != -1) {         switch (i) {             case 'a':                 printf("a = %s\n", optarg);                break;              case 'b':                 printf("b = %s\n", optarg);                break;              case 'c':                 printf("c = %s\n", optarg);                break;              default:                 break;         }     }      return 0; }     

i want program print out each of values passed e.g.

a = 0 b = 1 c = 2 

however not printing out @ all.

you forget ":" after option argument. if change 1 line

while ((i = getopt(argc, argv, "a:b:c:")) != -1) { 

you working variant.

read man 3 getopt, said third argument of getopt

… optstring string containing legitimate option characters. if such character followed colon, option requires argument, getopt() places pointer following text in same argv-element, or text of following argv-element, in optarg. 2 colons mean option takes optional arg; if there text in current argv-element (i.e., in same word option name itself, example, "-oarg"), returned in optarg, otherwise optarg set zero. …


Popular posts from this blog

How to calculate SNR of signals in MATLAB? -

c# - Attempting to upload to FTP: System.Net.WebException: System error -

ios - UISlider customization: how to properly add shadow to custom knob image -