10. Command Line Arguments#
As with Python, command line arguments in C++ provide a mechanism to pass information into a program when it is invoked from the command line. In Python, we accessed these from the sys.argv list. In C++, we access directly from the arguments to the main function using the parameters argc and argv.
argcprovides the number of command-line argumentsargvprovides an array of c-style strings representing the various command-line arguments. argv[0] is the name of the program that was invoked. (Hence, there’s always at least one command-line argument present.)
To make our lives easier in C++, we can easily convert argv into a vector of string objects.
1//filename: command.cpp
2//complile: g++ -std=c++17 -o command command.cpp
3//execute: ./command arg1 arg2 ... argn
4#include <iostream>
5#include <vector>
6#include <string>
7
8using std::cin, std::cout; // bring in these names from the std namespace
9using std::string, std::vector;
10
11int main(int argc, char *argv[]) {
12 std::vector<std::string> arguments(argv, argv + argc); // to skip the program name, add + 1 to argv
13 // in the first argument
14
15 cout << "Command-line arguments:" << "\n";
16 for (string argument: arguments) {
17 cout << argument << "\n";
18 }
19
20}
Use different command line arguments to see how the output changes: Execute: ./command arg1 arg2 ... argn
10.1. Practice - Add Program#
To practice, try writing a program that takes two command-line arguments in addition to the program names and adds them together. Attempt to convert both arguments to integers. If successful, add them and display the result. If not, concatenate the two commands together and output the result. Check to make sure the user entered the correct number of arguments. If not, display a usage statement and return with EXIT_FAILURE.
The strings notebook documents converts a string into a number and the exceptions notebook contains a slightly more refined version. You’ll need to also use a try-catch clause. add_solution.cpp contains the solution.
1//filename: add.cpp
2//complile: g++ -std=c++17 -o add add.cpp
3//execute: ./add
4#include <iostream>
5#include <vector> \
6#include <string>
7
8using std::cin, std::cout, std::endl;
9using std::string, std::vector;
10
11int main(int argc, char *argv[]) {
12
13}