Programs can receive data when executed from a command line or shell by accepting commend-line arguments. These arguments are passed as strings to the main function.
Accessing Command-Line Arguments
The standard signature for main in C++ includes parameters to handle these arguments:
int main(int argumentCount, char* argumentVector[])
argumentCount(conventionallyargc): An integer representing the total number of arguments passed, including the program's own name.argumentVector(conventionallyargv): An array of C-style strings (char*), where each element is one argument.argumentVector[0]always holds the program's invocation name.
An equivalent declaration uses a pointer to a pointer: int main(int argumentCount, char** argumentVector).
Example: Printing Arguments
A simple program to print received arguments:
#include <iostream>
int main(int argQuantity, char* argArray[]) {
for (int idx = 0; idx < argQuantity; ++idx) {
std::cout << "Argument " << idx << ": " << argArray[idx] << '\n';
}
return 0;
}
Parsing Coordinate Arguments
A common task is parsing string arguments representing coordinates into numeric values. The following example expects arguments in a format like x,y (e.g., 10,20) and converts them to integers.
#include <iostream>
#include <cstdlib> // For strtol
int main(int paramCount, char* paramValues[]) {
const int MAX_POINTS = 10;
int coordinates[MAX_POINTS][2] = {{0}}; // Store x,y pairs
int pointIndex = 0;
// Start from 1 to skip the program name (paramValues[0])
for (int argIdx = 1; argIdx < paramCount && pointIndex < MAX_POINTS; ++argIdx) {
char* currentArg = paramValues[argIdx];
int coordPos = 0; // 0 for x, 1 for y
char* start = currentArg;
char* end;
while (*start && coordPos < 2) {
// Convert part of the string to a long integer
long value = std::strtol(start, &end, 10);
if (start == end) {
// No conversion happened; move past non-digit
++start;
} else {
coordinates[pointIndex][coordPos] = static_cast<int>(value);
++coordPos;
start = end;
}
// Skip the comma separator if present
if (*start == ',') {
++start;
}
}
++pointIndex;
}
// Output the parsed coordinates
for (int i = 0; i < pointIndex; ++i) {
std::cout << "Point " << i << ": (" << coordinates[i][0] << ", " << coordinates[i][1] << ")\n";
}
return 0;
}
Converting String Arguments to Numeric Types
Command-line arguments are strings (char*). The C Standard Library provides functions for conversion in the <cstdlib> header.
int atoi(const char* str): Converts a string to an integer. It has limited error hendling.long strtol(const char* str, char** endptr, int base): A more robust function converting a string to a long integer. It allows specifying a numeric base (e.g., 10 for decimal) and provides a way to detect conversion errors via theendptrargument.double atof(const char* str): Converts a string to a double-precision floating-point number.
Example using strtol for safer conversion:
#include <iostream>
#include <cstdlib>
int main(int argc, char* argv[]) {
if (argc > 1) {
char* conversionEnd;
long numericValue = std::strtol(argv[1], &conversionEnd, 10);
if (*conversionEnd == '\0') { // Check if the entire string was converted
std::cout << "Parsed integer: " << numericValue << '\n';
} else {
std::cout << "Invalid number format.\n";
}
}
return 0;
}
For modern C++, the <string> header and std::stoi, std::stol, etc., offer a more C++-idiomatic approach with exception-based error handling.