how to get command arguments c++
#include <iostream>
int main(int argc, char *argv[]) {
std::cout << "Number of arguments: " << argc << std::endl;
for (int i = 0; i < argc; ++i) {
std::cout << "Argument " << i << ": " << argv[i] << std::endl;
}
return 0;
}
Explanation:
- #include <iostream>
: Includes the necessary library for input and output operations.
- int main(int argc, char *argv[])
: Defines the main function that accepts command-line arguments.
- argc
is an integer representing the number of arguments passed to the program.
- argv
is an array of strings (char *
) that holds the actual arguments.
- std::cout << "Number of arguments: " << argc << std::endl;
: Outputs the number of arguments passed to the program.
- for (int i = 0; i < argc; ++i) { std::cout << "Argument " << i << ": " << argv[i] << std::endl; }
: Loops through each argument and prints its index and value.
- return 0;
: Indicates successful execution of the program.