article

Command-line arguments, how to use them

Email
Submitted on: 1/2/2015 5:14:00 AM
By: Eric Gesinski (from psc cd)  
Level: Beginner
User Rating: By 6 Users
Compatibility: C++ (general), Microsoft Visual C++, Borland C++, UNIX C++
Views: 269
 
     A very basic run-through of how to implement command-line arguments, with code.

 
				Want to know how to use C++ with arguments? There's not too much code to do it, the basic part of it is adding parameters to your main function.


You need two parameters, one for the number of arguments that are entered (argc), and one for the arguments themselves (argv). These are an integer and a two-dimensional character array, respectively. These two dimensions are for 1) an array of characters (a string) and 2) the list of strings. To make it two-dimensional, you can do it in two different ways: either putting **argv or *argv[]. I like the second one, myself.

A few other things to know: in C++, the program itself is considered the first argument. So you really always have at least one argument, the program call itself. Also, the argc and argv variables are automatically set when you run the program, and they can be different every time you run it.

Here's a little program to show you exactly how to do this:

// Here's the standard include, you'll need it
// for the "cout" command.
#include <iostream.h>

// Now here's where you need to add
// the "argc" and "argv" parameters.
int main(int argc, char *argv[])
{
// Checking to see if there's only one
// argument (the program).
if (argc == 1)
{
cout << "There aren't any arguments!\n";
cout << "Just the program, \"" << argv[0] << "\".\n";
}
// Otherwise, there will be arguments.
else
{
cout << "Here are your arguments:\n";

// I used a for loop to go through
// the list of arguments, starting
// with the one after the program.
for (int i = 1; i < argc; i++)
cout << "\t" << argv[i] << endl;
}

return 0;
}


This is my first submission, so if the HTML tags are a little messed up, I'm still learning how to submit.

If you have any questions, or requests, just let me know - I'd be happy to help.


Report Bad Submission
Use this form to tell us if this entry should be deleted (i.e contains no code, is a virus, etc.).
This submission should be removed because:

Your Vote

What do you think of this article (in the Beginner category)?
(The article with your highest vote will win this month's coding contest!)
Excellent  Good  Average  Below Average  Poor (See voting log ...)
 

Other User Comments


 There are no comments on this submission.
 

Add Your Feedback
Your feedback will be posted below and an email sent to the author. Please remember that the author was kind enough to share this with you, so any criticisms must be stated politely, or they will be deleted. (For feedback not related to this particular article, please click here instead.)
 

To post feedback, first please login.