Skip to main content
GameDev.net gamedev.net
🔒 Locked

Command Line Arguments

Started by NashuNatta Jun 15, 2004 at 9:08 AM 2 replies 600+ views
Original Post
NashuNatta
NashuNatta
I have been having some trouble understanding the implementation of command line arguments. The tutorials that I read on google help, but can't realy answer my questions.

#include <iostream>
using namespace std;

int main(int argc,char *argv[])
Now from what I understand, the argc will check to see how many arguments are there, so if I were to type into my dos prompt app.exe -a -b -c it would see 3 arguments correct because the app itself doesnt count as an argument.Now, the argc is what is checking this right? Now, the big thing that I am having trouble comprehending is, is *argv[] checking what each of the commands is? For instance, say I had an app called math. The variables were set in the program to be 10 and 10. So say I called math.exe from my command prompt and added -a for add so... math.exe -a would come out to 20. How do I check within my program to see that I called -a? Is that were *argv[] comes in? This is what has been confusing me.
____________[email=UntimelyDeathProductions@yahoo.com][E-mail me][/email]
Monder
Monder
Actually for app.exe -a -b -c argc would 4 (name used to invoke the application does count). char* argv[] is basically an array of char*s. Each of the char*s in the argv array points to a different argument, so in your math.exe -a example if you wanted to check for -a you would do something like

if(!strcmp("-a", argv[1])){  //add numbers}


Note it checks for -a against argv[1], argv[0] will contain the program name (math.exe).
Fruny
Fruny
The argv parameter is an array of C (null-terminated) strings (that is, char*). argv[0] is always the name of the executable itself. Then for each argument (delimited by spaces), the array contains one string. The [] indicates that the size of the array is not a-priory known.

So if you wanted to check that "-a" is in the argument list you would go like:

bool a_flag = false;int main(int argc, char* argv[]){   for(int i=1; i<argc; ++i)   {     if(!strcmp(argv, "-a")) a_flag = true;   }}


And then use the value of a_flag. Depending on your platform, you may actually have a library function that does command line parsing for you (e.g. getopt).
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
Jingo
Jingo
argv[0] can be "" as well as the name of the program ("" being an empty string).

argv[argc] is always zero.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.