+ 3
Main arguments
int main (int argc, char *argv[]) I read that there are arguments for main too like in the above syntax. But I cannot how,where and when to use them. Please tell me if you know??
4 Réponses
+ 1
argc is the count of the arguments and argv is the array of arguments that are passed to the program.
Arguments can be passed to the program via the command line. Say you had a program called "proggy" and you ran "proggy -menu" from the command prompt. The "-menu" argument would be stored in argv[0] of the array. Then you could loop over the argv array in your program and check for valid values and run code depending on those values. For instance opening a menu for proggy.
+ 3
So do I need to build the program as .exe and what if I don't know how many arguments will the user pass means that if some have default arguments then.
+ 1
Let's say your program is called mega.exe and you called it on the command line like this:
c:\mega.exe John Sally
Then add this inside main:
for(int i=0; i < argc; i++)
cout << argv[i] << endl;
The output will be:
mega
John
Sally
Note you always get the name of your program as the 1st command line argument string. So even if you pass no "other" command line arguments, there will always be one - the name of the exe.
+ 1
@Megatron: Sorry, my apologies for the late reply - I missed your response somehow.
No, you don't need to have an EXE - most mainstream languages (even those running inside a VM) also gets the command line arguments in the function that serves as entry point - normally the VM/intepreter is invoked with these command line args - which passes it to the script/app is it executing.
For example, the Java main function is defined as:
public static void main(String[] args) {
The command line args is passed as a dynamic array of strings.
Regarding your second point - yes, you are right: you cannot know in advance how many default args your user will use so, yes, you have to cater for that so for the unused ones you will need default values.
But you will need default values anyway because the command line args is just to allow the user to pick between different existing "options", not define new options. Sot the standard way to handle is to set the default mode, and allow the user to override that using a command line args.
Typically you can get the command line args that are supported by running:
AppName /?
In this call there is just 1 command line arg (/?), but the typical behaviour should be that the app should then print all the command line args it supports.
For example, this is what an old version of rc.exe (Microsoft resource compiler) produces:
c:\rc /?
Microsoft (R) Windows (R) Resource Compiler Version 5.2.3690.0
Copyright (C) Microsoft Corporation. All rights reserved.
Usage: rc [options] .RC input file
Switches:
/r Emit .RES file (optional)
/v Verbose (print progress messages)
/d Define a symbol
/u Undefine a symbol
/fo Rename .RES file
/l ...etc...