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…
Your
sscanfcall is trying to read anything up to (but not including) the first-in the string. Since the-is (presumably) the first character, itauxends up empty.You could do something like:
sscanf(argv[1], "%*[-]%d", &n);. This will skip across any leading-characters, so arguments of23,-23and--23will all be treated identically. If you want--23to be interpreted as-23(only the one leading dash signals a flag), then you could usesscanf(argv[1], "-%d", &n);(and in this case, with just23on the command line, the conversion will fail outright).