C语言中argc与argv怎么用?为什么我初始化argc时候老是出错??

如题所述

argc与argv[]是启动C程序时系统传入的,可以直接使用。argc是参数数量,argv是参数表数组。如命令行为“prg.exe 1 2 3”,则argc为4,argv[0]="prg.exe",argv[1]="1",argv[2]="2",argv[3]="3"。以下是LCC-WIN32模板文件(加了一行显示所有参数语句):
/* --- The following code comes from e:\\lcc\\lib\\wizard\\textmode.tpl. */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void Usage(char *programName)
{
fprintf(stderr,"%s usage:\
",programName);
/* Modify here to add your usage message when the program is
* called without arguments */
}

/* returns the index of the first argument that is not an option; i.e.
does not start with a dash or a slash
*/
int HandleOptions(int argc,char *argv[])
{
int i,firstnonoption=0;

for (i=1; i< argc;i++) {

if (argv[i][0] == '/' || argv[i][0] == '-') {

switch (argv[i][1]) {

/* An argument -? means help is requested */

case '?':

Usage(argv[0]);

break;

case 'h':

case 'H':

if (!stricmp(argv[i]+1,"help")) {

Usage(argv[0]);

break;

}

/* If the option -h means anything else

* in your application add code here

* Note: this falls through to the default

* to print an "unknow option" message

*/

/* add your option switches here */

default:

fprintf(stderr,"unknown option %s\
",argv[i]);

break;

}

}
else {

firstnonoption = i;

break;

}
}
return firstnonoption;
}

int main(int argc,char *argv[])
{
if (argc == 1) {

/* If no arguments we call the Usage routine and exit */

Usage(argv[0]);

return 1;
}
/* handle the program options */
HandleOptions(argc,argv);
/* The code of your application goes here */

for (int i=0;i<argc;i++)printf("%s ",argv[i]);

return 0;
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2015-10-27
都是main函数的参数,解释如下:
argc:命令行总的参数的个数,即argv中元素的格式。
*argv[ ]:字符串数组,用来存放指向你的字符串参数的指针数组,每一个元素指向一个参数。
argv[0]:指向程序的全路径名。
argv[1]:指向在DOS命令行中执行程序名后的第一个字符串。
argv[2]:指向第二个字符串。
相似回答