README.md
December 5, 2022 · View on GitHub
Description
A very basic run-through of how to implement command-line arguments, with code.
More Info
| Submitted On | |
| By | Eric Gesinski |
| Level | Beginner |
| User Rating | 4.3 (26 globes from 6 users) |
| Compatibility | C++ (general), Microsoft Visual C++, Borland C++, UNIX C++ |
| Category | Miscellaneous |
| World | C / C++ |
| Archive File |
Source 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.