Spis treści

Pobieranie argumentów podczas uruchamiania programu konsolowego

int zmienna1 = atoi (argv[1]);
int zmienna2 = atoi (argv[3]);

Funkcja parsująca parametry wywołania programu w C++ z ich nazwami

inline const char*  getCmdOption(const char * name, const char * defaut, const int argc, const char *const * argv)
{
  const char *res = 0;
  
  if (argc > 0) {
    int k = 0;
    while (k < argc && strcmp(argv[k],name)) ++k;
    res = (k++==argc?defaut:(k==argc?argv[--k]:argv[k]));
  } else res = defaut;
  
  return res;
}

Przykładowe użycie funkcji getCmdOption:

if (argc == 1) {
  printf("Usage: %s -f filename.raw -dx [value] -dy [value] -dz [value]\n", argv[0]);
  exit(0);
}

const char * filename  = getCmdOption("-f",    (char*)0, argc, argv );
const char * _dx       = getCmdOption("-dx",   (char*)0, argc, argv );
const char * _dy       = getCmdOption("-dy",   (char*)0, argc, argv );
const char * _dz       = getCmdOption("-dz",   (char*)0, argc, argv );

if ((char*)0 == filename) { 
  printf("Please specify input data file name (-f)\n"); 
  exit(0);
}
if ((char*)0 == _dx || (char*)0 == _dx || (char*)0 == _dx) { 
  printf("Please specify input data dimension sizes (-dx, -dy, -dz)\n"); 
  exit(0);
}

int dx = atoi( _dx );
int dy = atoi( _dy );
int dz = atoi( _dz );

http://rpetryniak.blogspot.com/2011/04/obsuga-parametrow-wywoania-programu-w-c.html