C语言执行程序时加入参数 int main ( int argc, char *argv[ ] )
在主函数入口处添加形参int argc , char *argv[ ];argc 是执行程序时传入的参数(字符串)个数;argv 指针数组是存放传入的参数(字符串)地址;一个小例子:/*test_main.c*/#include <stdio.h>int main(int argc, char *argv[]){printf("%d\n",argc);...
·
在主函数入口处添加形参int argc , char *argv[ ];
argc 是执行程序时传入的参数(字符串)个数;
argv 指针数组是存放传入的参数(字符串)地址;
一个小例子:
/*test_main.c*/
#include <stdio.h>
int main(int argc, char *argv[])
{
printf("%d\n",argc);
printf("\n");
printf("%s\n",argv[0]);
printf("%s\n",argv[1]);
printf("%s\n",argv[2]);
return 0;
}
/*ecec*/
yu@ubuntu:~/ $ ./test_main.o wan tu sirui
4
./test_main.o
wan
tu
我执行程序时只添加了3个参数,它却显示4个,原因就是执行的程序也算是一个参数。
传入的参数是当成字符串处理的,当然也可以转换成其他类型
yu@ubuntu:~/ $ cat test_main.c
#include <stdio.h>
int main(int argc, char *argv[])
{
printf("%d\n",*argv[1] - '0');
return 0;
}
yu@ubuntu:~/ $ ./test_main.o 5
5
直接把字符串5转换成int型5了,当然仅限单个字符;
如果是多个字符,可以参考我其他文章写的转换方法,char转int型或float型。
更多推荐
已为社区贡献1条内容
所有评论(0)