⌨️ Command Line Arguments in C++ — argc, argv and Parsing User Input
Read command line arguments in C++ with argc and argv. Learn how to parse flags, convert strings to numbers and build CLI tools — with practical examples.
Every C++ program can accept inputs from the command line. The trick: declare main with two parameters.
📜 The signature
int main(int argc, char* argv[]) {
// argc = ARGument Count (number of args)
// argv = ARGument Vector (array of C-strings)
}🔑 Key facts
argv[0]= the program's own name (or path)argv[1]= first actual argumentargv[argc]= nullptr (sentinel)- All arguments come in as C-strings — convert if you need numbers
🔢 String → number
int n = std::stoi(argv[1]); // throws on invalid input
double d = std::stod(argv[2]);💡 Modern style: collect args into a vector
#include <vector>
#include <string>
std::vector<std::string> args(argv + 1, argv + argc);💻 Code Examples
Print all arguments
int main(int argc, char* argv[]) {
std::cout << "Got " << argc << " args\n";
for (int i = 0; i < argc; i++) {
std::cout << i << ": " << argv[i] << '\n';
}
}Output:
$ ./app hello world Got 3 args 0: ./app 1: hello 2: world
Simple calculator from CLI
int main(int argc, char* argv[]) {
if (argc != 3) {
std::cerr << "Usage: " << argv[0] << " <a> <b>\n";
return 1;
}
int a = std::stoi(argv[1]);
int b = std::stoi(argv[2]);
std::cout << a + b;
}Output:
$ ./sum 5 7 12
⚠️ Common Mistakes
- Forgetting that `argv[0]` is the program name, not the first user arg.
- Not validating `argc` before accessing `argv[1]` — crash if missing.
- Using `atoi` instead of `std::stoi` — atoi silently returns 0 on bad input, hiding bugs.
- Assuming args are typed — they're always strings; convert explicitly.
🎯 Interview Questions
Real questions asked at top product and service-based companies.
Q1.What do argc and argv mean in main()?Beginner
argc = Argument Count, the number of command-line arguments including the program name. argv = Argument Vector, an array of C-strings holding each argument. argv[0] is the program name; argv[1..argc-1] are user-provided args.
Q2.How do you convert a command-line argument to an integer?Beginner
Use std::stoi(argv[i]) — throws std::invalid_argument or std::out_of_range on bad input. The older atoi(argv[i]) silently returns 0 on failure, which is unsafe.
Q3.What's argv[argc]?Intermediate
It's always nullptr — a sentinel value marking the end of the argument list. Useful for loops that iterate while *p != nullptr.
Q4.How would you implement a flag parser like -v or --verbose?Intermediate
Loop through argv, compare each string with std::string(argv[i]) == "-v" || std::string(argv[i]) == "--verbose". For complex CLIs, use a library like CLI11 or boost::program_options.
🧠 Quick Summary
- main(int argc, char* argv[]) receives CLI input.
- argv[0] = program name; argv[1..] = user arguments.
- All arguments are C-strings — convert with std::stoi/stod.
- Always validate argc before accessing argv[i].
- For complex CLIs, use a parsing library.