how to deal with argv in c++ code example

Example 1: c++ argv

// command line arguments in c++ are stored in an array of c-strings
// # of arguments: argc
// actual arguments: argv

#include <iostream>
using namespace std;

int main(int argc, char** argv){
  for(int i = 0; i < argc; i++){
    cout << "argv" << i << ": " << argv[i] << endl;
  }
  return 0;
}

/*

./main.exe hello world

argv0: main.exe
argv1: hello
argv2: world

*/

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