If you don't have any other command line options you need to handle, getopt
is probably overkill. All you need is to read the value from argv
:
int main(int argc, char *argv[])
{
int n;
// need "2 args" because the program's name counts as 1
if (argc != 2)
{
fprintf(stderr, "usage: square <n>\n");
return -1;
}
// convert the first argument, argv[1], from string to int;
// see note below about using strtol() instead
n = atoi(argv[1]);
square(n);
return 0;
}
A better solution will use strtol()
instead of atoi()
in order to check if the conversion was valid.