Search code examples
cscanfargvatoi

How to get first argument of a program call


I'm making a program in C and this is my code:

int main(int argc, char **argv) {
    int n;
    char aux[10];
    sscanf(argv[1], "%[^-]", aux);
    n = atoi(aux);
}

So, if I run the program from command line: my_program -23, I want to get the number "23" to isolate it in a var like an integer, but this don't work and I don't know why...


Solution

  • Your sscanf call is trying to read anything up to (but not including) the first - in the string. Since the - is (presumably) the first character, it aux ends up empty.

    You could do something like: sscanf(argv[1], "%*[-]%d", &n);. This will skip across any leading - characters, so arguments of 23, -23 and --23 will all be treated identically. If you want --23 to be interpreted as -23 (only the one leading dash signals a flag), then you could use sscanf(argv[1], "-%d", &n); (and in this case, with just 23 on the command line, the conversion will fail outright).