c - how to take integers as command line arguments? -


i've read a getopt() example doesn't show how accept integers argument options, cvalue in code example:

 #include <ctype.h>  #include <stdio.h>  #include <stdlib.h>  #include <unistd.h>   int  main (int argc, char **argv)  {    int aflag = 0;    int bflag = 0;    char *cvalue = null;    int index;    int c;     opterr = 0;     while ((c = getopt (argc, argv, "abc:")) != -1)      switch (c)        {        case 'a':          aflag = 1;          break;        case 'b':          bflag = 1;          break;        case 'c':          cvalue = optarg;          break;        case '?':          if (optopt == 'c')            fprintf (stderr, "option -%c requires argument.\n", optopt);          else if (isprint (optopt))            fprintf (stderr, "unknown option `-%c'.\n", optopt);          else            fprintf (stderr,                     "unknown option character `\\x%x'.\n",                     optopt);          return 1;        default:          abort ();        }     printf ("aflag = %d, bflag = %d, cvalue = %s\n",            aflag, bflag, cvalue);     (index = optind; index < argc; index++)      printf ("non-option argument %s\n", argv[index]);    return 0;  } 

if ran above testop -c foo, cvalue foo, if wanted testop -c 42? since cvalue of type char *, cast optarg (int)? i've tried doing without using getopt() , accessing argv[whatever] directly, , casting integer, end large negative number when printing %d. i'm assuming i'm not dereferencing argv[] correctly or something, not sure...

you need use atoi() convert string integer.


Comments

Popular posts from this blog

java - SNMP4J General Variable Binding Error -

windows - Python Service Installation - "Could not find PythonClass entry" -

Determine if a XmlNode is empty or null in C#? -