C++ has the ability to accept command-line or user-defined arguments to modify the behavior of a program. Arguments are passed to the main function as parameters, where the first parameter is always the number of arguments (including the program name) and the second parameter is the array of arguments.
Here are some code examples using arguments in C++:
// Example 1: Printing out command-line arguments #include using namespace std;
int main(int argc, char* argv[]) { for (int i = 0; i < argc; i++) { cout << "Argument " << i << ": " << argv[i] << endl; } return 0; }
// Example 2: Adding user-defined numbers #include #include // for atoi function using namespace std;
int main(int argc, char* argv[]) { int sum = 0; for (int i = 1; i < argc; i++) { // start from 1, ignore program name int num = atoi(argv[i]); // convert argument to integer sum += num; } cout << "Sum: " << sum << endl; return 0; }
In Example 1, the program simply prints out all the arguments passed to it. In Example 2, the program adds up all the user-defined numbers and prints out the sum.
The package library for this is the C++ Standard Library.
C++ (Cpp) Arguments - 30 examples found. These are the top rated real world C++ (Cpp) examples of Arguments from package Astade extracted from open source projects. You can rate examples to help us improve the quality of examples.