I would like a program to read in a file entered by the user via the command line, which is then used in the main body of the code.
See example code below:
#include <iostream>
#include <fstream>
struct run_t {
std::string file;
};
run_t run;
const POINTER* ptr = toy(run.file, 0);
// Here hardcoded the FILENAME as a string => code works.
// I am trying to get it to work when I read in the filename from the
// first entry on the command line upon program execution:
//
//const POINTER* ptr = toy("FILENAME", 0);
double Toy1(double a, double b, double c) {
return ptr->func(a, b, c);
};
double Toy2(double d) {
double factor = pow(d, 2); //some dummy prefactor
return factor * Toy1(4, 5, 6);
};
int main(int argc, char* argv[])
{
run_t run;
run.file = argv[1];
std::cout << Toy2(1) << std::endl;
return 0;
}
The actual toy
and Toy
functions are software-specific and recognised by additional include-files. If I manually hardcode run.file
in toy(run.file, 0)
with the string FILENAME
, compile and execute with a single command line parameter (./exe 1
, say) then the program works.
My question is, how to modify the above code so that the value FILENAME
entered in the command line is read in instead as run.file
? That is, to make ./exe FILENAME
work? I have tried with declaring argv[1]
as the argument of toy but I have not yet got this to work.
Here is the code I have tested. Try this
#include <iostream>
#include <fstream>
#include <math.h>
struct run_t {
std::string file;
};
run_t run;
class POINTER{
public:
POINTER(std::string file , int num){std::cout << "POINTER::POINTER(std::string file , int num)file " << file << std::endl;};
double func(double a, double b, double c) {
POINTER *toy(std::string file , int num);
return (double)0;
}
};
POINTER *toy(std::string file , int num)
{
POINTER* ptr = new POINTER(file , num);
std::cout << "POINTER *toy(std::string file , int num) file " << file << std::endl;
return ptr;
}
const POINTER * ptr;
double Toy1(double a, double b, double c) {
POINTER * ptrCst = const_cast<POINTER *>(ptr);
return ptrCst->func(a, b, c);
};
double Toy2(double d) {
double factor = pow(d, 2); //some dummy prefactor
return factor * Toy1(4, 5, 6);
};
int main(int argc, char* argv[])
{
run.file = argv[1];
POINTER * ptrCst = const_cast<POINTER *>(ptr);
ptrCst = toy(run.file, 0);
std::cout << Toy2(1) << std::endl;
while(1);
return 0;
}