6.3 Command-line Arguments
A program can receive arguments from the command line. argc is the argument count, and argv stores those arguments as strings.
cpp
#include <iostream>
int main(int argc, char* argv[]) {
if (argc != 2) {
std::cerr << "Usage: " << argv[0] << " file.txt" << std::endl;
return 1;
}
std::cout << "processing " << argv[1] << std::endl;
return 0;
}argv[0] is usually the program name, argv[1] is the first user argument, and so on. Every argument is a string, so convert them with std::atoi() from <cstdlib> or std::stoi() from <string> when you need numbers.
cpp
int times = std::atoi(argv[1]); // "3" -> 3Write error messages to stderr and normal results to stdout. In C++, std::cerr writes to stderr, and std::cout writes to stdout. That way users can redirect normal output to a file while still seeing errors in the terminal.
bash
./greet Ada > out.txtLoading interactive lab...
Loading concept check...
Loading practice...