如果您没有任何其他命令行选项需要处理,getopt则可能是矫枉过正.您只需要读取以下值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;
}
Run Code Online (Sandbox Code Playgroud)
将使用strtol()atoi()更好的解决方案,而不是检查转换是否有效.