input from command line example

October 26 2022 11:39:22.




#if __has_include("iostream")
#include <iostream>
#define CXX
#else
#include <stdio.h>
#include <stdlib.h>
#endif

int main(const int argc, const char* argv[])
{
#ifndef CXX // c
printf(" C version \n");
#else // c++
std::cout<<" C++ version" <<std::endl;
#endif
for(int i=0; i<argc; ++i)
{
printf("input arg[%d]: \t %s \n",i,argv[i]);
if(i>0)
{
// how to convert a char* to a numerical

#ifndef CXX // c
const int n = atoi(argv[i]);
printf("converted to int:\t %d \n",n);
const double x = atof(argv[i]);
printf("converted to double:\t %lf \n",x);
//more robust cross-platform
/* https://cplusplus.com/reference/cstdlib/strtol/ */
const long int l = strtol(argv[i], NULL, 10);
printf("converted to int:\t %ld \n",l);
/* https://cplusplus.com/reference/cstdlib/strtod/ */
const double y = strtod(argv[i], NULL);
printf("converted to double:\t %lf \n",y);
#else // c++
const int m = std::stoi((argv[i]));
std::cout<< "converted to int: \t" << m <<std::endl;
const double z = std::stod(std::string(argv[i]));
std::cout<< "converted to double: \t" << z <<std::endl;
// check what happens by passing a non-numeric
#endif
}
}
return 0;
}