When the user starts the program by entering the executable file name in the CMD window, the strings following the executable file name are called " command line parameters ". There can be multiple command line arguments, separated by spaces. For example, type in the CMD window:
copy file1.txt file2.txt
"copy" , "file1.txt" , "file2.txt" are command line parameters
How do I get command line arguments in a program?
int main(int argc,char *argv[])
{
...
}
argc: Represents the number of command line arguments when starting the program. The C/C++ language stipulates that the file name of the executable program itself is also a command line parameter, so the value of argc is at least 1.
argv: An array of pointers, each element of which is a pointer of type char*, which points to a string, and the command line parameters are stored in this string.
For example, the string pointed to by argv[0] is a command line parameter, that is, the file name of the executable program, argv[1] points to the second command line parameter, argv[2] points to the third...
//示例
#inclde<stdio.h>
int main(int argc,char *argv[])
{
for (int i=0;i<argc;i++)
printf("%s\n",argv[i]);
return 0;
}
Compile the above program into sample.exe, and then type in the console window:
sample para1 para2 s.txt 5 "hello world"
Output result:
sample
para1
para2
s.txt
"hello world"