Home > Software design >  How to get correct number from args?
How to get correct number from args?

Time:02-15

I write an application, which get a number from args.

ex:./app --addr 0x123 or ./app --addr 123

I don't know which api can identify if the parameter is hex or decimal and come up with the correct data?

Thanks.

CodePudding user response:

strtol will do the job for you

https://www.cplusplus.com/reference/cstdlib/strtol/

CodePudding user response:

One way of getting the arguments is through argc and argv in

int main(int argc, char* argv[]) {
    // Some code here.
    return;
}

This will give you an array with all the arguments as strings. For example:

#include <iostream>

int main(int argc, char* argv[]) {
    for (int i{ 0 }; i < argc; i  )
        std::cout << "Argument " << i << ": " << argv[i] << std::endl;
    return;
}

will give you this output

$ ./app --addr 0x123
Argument 0: ./app
Argument 1: --addr
Argument 2: 0x123

Now, parsing the input is a bit more complicated. You could create your own logic to evaluate the arguments once you have the arguments as strings.

You could also use libraries. For example, you could use argparse by p-ranav. GitHub repository here. It is an easy to use library so you don't have to worry about positioning of the arguments.

Answering you question, how do you know if the input is hex or decimal? You could check if the argument after --addr starts with 0x or not. That could be one way, but you have to also consider the case when someone inputs a hex value without the 0x, like ./app --addr A2C. Also, documenting acceptable formats and printing a --help message can ameliorate this.

You have to think about your specific application, but some steps once you have the string after --addr that you could do to check input is:

  • Does it start with 0x?
  • If not, does it contains characters 0-1 and A-F? Is this allowed?
  • Is it in a valid range?
    • For example, 0xFFFFF is 1,048,575. But you may only want addresses up to 0xFFFF (65,535). What should happen in these cases?

Hope it helps!

P.S.: These are all implementations in C .

  •  Tags:  
  • c c
  • Related