Find the answer to your Linux question:
Results 1 to 2 of 2
Hi, I'm writing a program in C, how can i specify a value with the -l command line option? and how do i use -s <num> option? And how do ...
  1. #1
    Just Joined!
    Join Date
    Feb 2007
    Posts
    12

    Various programming issues

    Hi,
    I'm writing a program in C, how can i specify a value with the -l command line option? and how do i use -s <num> option?

    And how do i pass an integer argument to the main function? how do i make sure an integer is passed and not a string? like instanceOf in Java?

    thanks

  2. #2
    Trusted Penguin Cabhan's Avatar
    Join Date
    Jan 2005
    Location
    Seattle, WA, USA
    Posts
    3,230
    So if you want to obtain commandline options, you can either process the argv array yourself, or use the glibc getopt function:

    http://www.gnu.org/software/libc/man...pt.html#Getopt

    As for passing an integer argument, argv consists entirely of strings. You can convert one to an int using glibc's atoi() function (see the man page) or manually using code rather like the following:

    Code:
    char *string = "123";
    int len = strlen(string);
    
    int val = 0;
    
    int i;
    for(i = 0; i < len; i++)
    {
        int pow = len - 1 - i;
    
        char digit = string[i];
        int digit_val = digit - '0';
        val += digit_val * pow(10, pow);
    }
    val now holds the value of the string in int form. This of course assumes that string is a base-10 integer. It relies on the pow function which is in math.h.
    DISTRO=Arch
    Registered Linux User #388732

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...