Question

I'm writing a small application in C that takes two parameters. One is a filename, the other a number, and they may be specified in random order.

./main filename 12345

and

./main 12345 filename

should both work.

How can I easily determine which is which when I know the filename starts with a character?

Was it helpful?

Solution

You can use the isalpha and isdigit functions (defined in ctype.h) on the first character of argv[1] or argv[2].

OTHER TIPS

You can use the ctype functions.

if (isalpha(*argv[1]))
    // argv[1] starts with a letter
else if (isdigit(*argv[1])
    // argv[1] starts with a number

Use isdigit.

isdigit((unsigned char)argv[1][0])

Make sure you check argc first.

if ('0' <= argv[1][0] && argv[1][0] <= '9')
{
    /* it starts with a number */
}

You can also use the sscanf() function, which returns the number of successfully scanned items:

int number;
char *string;

if (sscanf (argv[1], " %d ", &number) == 1) { /*12345 filename */
  string = malloc ((strlen (argv[2]) + 1) * sizeof (char));
  sscanf (argv[2], " %s ", string);
}
else { /* filename 12345 */
  sscanf (argv[2], " %d ", &number);
  string = malloc ((strlen (argv[1]) + 1) * sizeof (char));
  sscanf (argv[1], " %s ", string);
}

If argv[1] is a string starting with a character the first clause will return "zero".

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top