A long time ago in DOS applications, we used command-line arguments to execute applications such as:
Copy C:\1.txt D:\
In C + +, the transfer of command-line parameters is implemented using main for formal parameter delivery.
In the previous tutorial we did a definition of void main () or void main (void), which means that main does not return any type, and main does not have any arguments, but in the absence state Mian (), Formal parameters are always present in the stack space only to be hidden.
In order to implement the command-line arguments we will use the form of main (int argc,char* argv[]) to define ARGC and argv can be replaced by your own favorite name, not necessarily ARGV,ARGC these forms are just habits, char* argv[] As we've already talked about, this is a pointer array, argv is a pointer array name, ARGV is not a constant pointer, but a variable pointer with variable characteristics, it can be moved, so we can write char* *argv is correct, int ARGC This definition returns the number of parameters so it is marked as a cosmetic (int).
#include <iostream>
#include <string>
using namespace Std;
void Main (int argc,char* argv[])
{
int i=0;
while (I<ARGC)
{
cout<<*argv++<<endl;//It's right to rewrite this here as cout<<argv[i]<<endl;.
i++;
}
Cin.get ();
}
In the submission of command-line arguments, the system automatically adds a null to the array of pointers, so the code can be written in the following simple form, simplifying the code to improve efficiency.
#include <iostream>
#include <string>
using namespace Std;
void Main (int argc,char* argv[])
{
while (*argv!=null)//Here is written while (*ARGV) is also correct!
{
cout<<*argv++<<endl;
}
Cin.get ();
}
Finally, let's say the prototype of the complete command-line argument: void Main (int argc,char* argv[],char* env[])
Env used very little, usually used for the return of events, here is not discussed, the specific can query books.
void Main (int argc) omitting the definition of other parameters is also possible, so that the runtime returns the parameter mathematics directly without returning the other.
When you run a command-line argument with char* argv[], if the input parameter has an empty format, it should be enclosed in double quotes.
For example Test4.exe "Hello world!" ha ha