Archive

Posts Tagged ‘argc’

Multi-Argument Parsing

March 15th, 2010 admin No comments

Well, it has been some time since my last post since I have been (and still am) very busy, but I felt I needed to update! I wrote a quick script for you guys to help in any programming endeavors you may be having parsing your command line arguments in any command line program. This example merely shows how to simply print all the arguments given to a specified program, however, you can use this type of loop to do whatever you wish!

/**
* Process Command Line Args
* Level: Easy
* Author: Dennis J. McWherter, Jr.
*
*/

#include <iostream>

using namespace std; // I'll save myself some std::<> pain this time XD

void echo(char* str,int no)
{
int x = strlen(str);
cout<< "Argument Number "<< no << ": ";
for(int i=0;i<x;i++){
cout<< str[i];
}
cout<< endl;
}

int main(int argc,char* argv[])
{
for(int i=1;i<argc;i++){
echo(argv[i],i);
}
cout<< endl<< "Command line: "<< argv[0] << endl;
return 0;
}

As you can see, the first function is a loop which is given a char* array (it loops through each array value to print out the full string) and an integer position. The int allows the script to know which argument number it is processing (not that it is imperative in this case). In the int main(); function, this void echo(); function is called in another for(); loop. This loop begins at array position 1 (the array starts at position 0, however, arguments begin at 1; 0 is the program/command line name). Therefore, for each argument listed the program loops until it reaches it has no further arguments to parse.

There is your quick lesson today in processing multiple arguments in the command line! This should help many of you looking for a quick and easy solution to do this! The example code is provided below for download.

Regards,
Dennis M.

Parse Multiple Arguments