相信大家用C語言定義main函數時,大多數人的寫法都是int main(void)。其實main函數是可以向其傳遞參數的,給個實例:
//給main函數傳參實例:
#include <stdio.h>
#include <string.h>
//int main(int argc, char *argv[])
int main(int argc, char **argv)
{
char *array[3] = {"./main", "hello", "world"};
if (argc < 2)
{
printf("error!\n");
printf("./main str\n");
return -1;
}
printf("The first string of your command is:%s\n", argv[0]);
printf("The second string of your command is:%s\n", argv[1]);
printf("The third string of your command is:%s\n", argv[2]);
if (!strcmp(argv[0], array[0]))
{
printf("The first command execute successfully!\n");
}
if (!strcmp(argv[1], array[1]))
{
printf("The second command execute successfully!\n");
}
if (!strcmp(argv[2], array[2]))
{
printf("The third command execute successfully!\n");
}
return 0;
}
輸出結果:
(1)若輸入命令為:./main
則輸出結果為:
error!
The command is:./main
(2)若輸入命令為:./main hello world
則輸出結果為:
The first string of your command is:./main
The second string of your command is:hello
The third string of your command is:world
The first command execute successfully!
The second command execute successfully!
The third command execute successfully!
大家可以利用這個程序模型干很多事呢!
C++ Primer Plus 第6版 中文版 清晰有書簽PDF+源代碼 http://www.linuxidc.com/Linux/2014-05/101227.htm
讀C++ Primer 之構造函數陷阱 http://www.linuxidc.com/Linux/2011-08/40176.htm
讀C++ Primer 之智能指針 http://www.linuxidc.com/Linux/2011-08/40177.htm
讀C++ Primer 之句柄類 http://www.linuxidc.com/Linux/2011-08/40175.htm
將C語言梳理一下,分布在以下10個章節中: