質問

So I'm finishing up with a project and there is only one thing left for me to do; handle the command line arguments properly. I thought I had them handled but apparently I'm wrong...There can be two different sets of command line arguments that can come in, here are examples of what I'm talking about: ./hw34 -c 385 280 50 balloons.ascii.pgm balloonCircle.pgm and ./hw34 -e 100 balloons.ascii.pgm balloonEdge.pgm

This is what I had tried to handle the arguments, but this didn't seem to work: if(argc==5) && isdigit(atoi(argv[2]))){ and else if(argc==7 && isdigit(atoi(argv[2])) && isdigit(atoi(argv[3])) && isdigit(atoi(argv[4]))){

What I'm stuck on is trying to figure out if argv[x] are numbers or not.

役に立ちましたか?

解決

You should probably try to handle your command line differently.

Something like:

./hw34 -c "385,280,50" balloons.ascii.pgm balloonCircle.pgm

./hw34 -e 100 balloons.ascii.pgm balloonEdge.pgm

Then combined with getopt for command line handling and strtok for argument list's splitting, you should be able to achieve what you want.

The main advantage is that you won't have to worry about the number of arguments or their position in your command line anymore.

他のヒント

argv is an array of strings. There are no integers.

You can easily test if conversion was possible by using strtol, and then check if all characters were consumed:

char const * str = "123";
char * endptr;
long number = strtol(str, &endptr, 0); // do the conversion to long integer
if(&str[strlen(str)] == endptr) // endptr should point at the end of original string
    printf("ok");
else
    printf("error");

Canonical main function with arguments prototype is

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

Where argc is the number of parameters, char* argv[] - an array of strings of these parameters. First element of the array - argv[0] - is the name of the program.

To check if the parameter is a number you can use strtol function which returns status of the conversion:

char* tail;
long n = strtol(argv[2], &tail, 10);  // 10 is the base of the conversion

Then check the tail which points to the part of the string after a number (if any):

if (tail == argv[2]) { // not a number
   // ...
} else if (*tail != 0) {  // starts with a number but has additional chars
   // ...
} else { // a number, OK
   // ...
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top