c++ arguments code example

Example 1: c++ variable arguments

#include <iostream>
#include <cstdarg>
using namespace std;

double average(int num,...) {
   va_list valist;               // A place to store the list of arguments (valist)
   double sum = 0.0;
   int i;
   
   va_start(valist, num);        // Initialize valist for num number of arguments
   for (i = 0; i < num; i++) {   // Access all the arguments assigned to valist
      sum += va_arg(valist, int);
   }
   va_end(valist);               // Clean memory reserved for valist
   
   return sum/num;
}

int main() {
   cout << "[Average 3 numbers: 44,55,66] -> " << average(3, 44,55,66) << endl;
   cout << "[Average 2 numbers: 10,11] -> " << average(2, 10,11) << endl; 
   cout << "[Average 1 number:  18] -> " << average(1, 18) << endl; 
}

/*
NOTE: You will need to use the following 'data_types' within the function
va_list   :  A place to store the list of arguments (valist)
va_start  :  Initialize valist for num number of arguments
va_arg    :  Access all the arguments assigned to valist
va_end    :  Clean memory reserved for valist
*/

Example 2: command line options in c++

// Use command lines

int main(int argc, char *argv[])
{

	for(int i = 1; i < argc; i++){
		if(!strcmp(argv[i], "-h") || !strcmp(argv[i], "--help") ){
			printf("Usage: App <options>\nOptions are:\n");
			printf("Option list goes here");
			exit(0);
		}else if(!strcmp(argv[i], "-c") || !strcmp(argv[i], "--custom")){
			printf("argument accepted");
		}else{
			if(i == argc-1){
				break;
			}
			MessageBox(NULL, TEXT("ERROR: Invalid Command Line Option Found: \"%s\".\n", argv[i]), TEXT("Error"), MB_ICONERROR | MB_OK);
		}
	}

	MessageBox(NULL, TEXT("ERROR: No Command Line Option Found. Type in --hep or -h"), TEXT("Error"), MB_ICONERROR | MB_OK);
}

Tags:

Cpp Example