ccommand-line-argumentsatoi

Parsing command line arguments for string/integer to stdout


Programs can be called with command line arguments. For example, a program printargs might be called as ./printargs -a2 -b4.

I want to implement a program that accepts two arguments -aA and -bB for integers A and B in arbitrary order, i.e. -aA -bB and -bB -aA are both legitimate arguments when calling your program and converts A and B to integers, and writes to stdout/terminal the line “A is (INSERT A) and B is (INSERT B)”.

For example calling

printargs -a2 -b4 or

printargs -b4 -a2 should output

A is 2 and B is 4

I have made some progress I think and I have written the following code:

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

int main( int argc, char *argv[])
{


int a,b;

a = atoi(argv[0]);
b = atoi(argv[1]);

printf("A is  %d and B is %d\n",a,b);

return 0;

}

I get the output in the Terminal - which is of course incorrect.

A is  0 and B is 0

when running the code/command

./print -a2 -b4

in the terminal

Can anyone help me out?

Thanks in advance


Solution

  • sscanf can be used to parse the arguments.
    Check that argc is 3.
    This will work with ./printargs -a3 -b45 or ./printargs -b45 -a3

    #include <stdio.h>
    #include <stdlib.h>
    
    int main ( int argc, char *argv[])
    {
        int a = 0;
        int b = 0;
        int j = 0;
    
        if ( argc != 3) {
            fprintf ( stderr, "Useage;\n\t%s -ax -by\n", argv[0]);
            return 1;
        }
    
        for ( j = 1; j < argc; ++j) {
            sscanf ( argv[j], "-a%d", &a);
            sscanf ( argv[j], "-b%d", &b);
        }
    
        printf ( "A is  %d and B is %d\n", a, b);
    
        return 0;
    }