C++ Primer main: 处理命令行选项

7.2.6. main: 处理命令行选项

It turns out that main is a good example of how C programs pass arrays to functions. Up to now, we have defined main with an empty parameter list:

主函数 main 是演示 C 程序如何将数组传递给函数的好例子。直到现在,我们所定义的主函数都只有空的形参表:

     int main() { ... }

However, we often need to pass arguments to main. TRaditionally, such arguments are options that determine the operation of the program. For example, assuming our main program was in an executable file named prog, we might pass options to the program as follows:

但是,我们通常需要给 main 传递实参。传统上,主函数的实参是可选的,用来确定程序要执行的操作。比如,假设我们的主函数 main 位于名为 prog 的可执行文件中,可如下将实参选项传递给程序:

     prog -d -o ofile data0

The way this usage is handled is that main actually defines two parameters:

这种用法的处理方法实际上是在主函数 main 中定义了两个形参:

     int main(int argc, char *argv[]) { ... }

The second parameter, argv, is an array of C-style character strings. The first parameter, argc, passes the number of strings in that array. Because the second parameter is an array, we might alternatively define main as

第二个形参 argv 是一个 C 风格字符串数组。第一个形参 argc 则用于传递该数组中字符串的个数。由于第二个参数是一个数组,主函数 main 也可以这样定义:

     int main(int argc, char **argv) { ... }

indicating that argv points to a char*.

表示 argv 是指向 char* 的指针。

When arguments are passed to main, the first string in argv, if any, is always the name of the program. Subsequent elements pass additional optional strings to main. Given the previous command line, argc would be set to 5, and argv would hold the following C-style character strings:

当将实参传递给主函数 main 时,argv 中的第一个字符串(如果有的话)通常是程序的名字。接下来的元素将额外的可选字符串传递给主函数 main。以前面的命令行为例,argc 应设为 5,argv 会保存下面几个 C 风格字符串:

     argv[0] = "prog";
     argv[1] = "-d";
     argv[2] = "-o";
     argv[3] = "ofile";
     argv[4] = "data0";
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值