Information Technology Reference
In-Depth Information
The Main Program
The main program (in the case where we use a primitive C/C CC array for u )is
listed below.
int main (int argc, const char * argv[])
{
// check that we have enough command-line arguments:
if (argc < 3) {
std::cout << "Usage: " << argv[0] << " tstop dt\n";
exit(1);
}
// read tstop and dt from the command line:
double tstop = atof(argv[1]); // get 1st command-line arg.
double dt = atof(argv[2]);
// get 2nd command-line arg.
if (dt < 0.0) { dt = 0.004; } // set a suitable time
step if dt<0
int n = int(tstop/dt);
// no of time steps
double * u = new double[n+1]; // create solution array
// time integration:
double u0 = 1.0; // initial condition
heun (f1, u0, dt, n, u); // advance solution n steps
printf("end value=%g error=%g\n", u[n], u[n]-exp(-dt * n));
// write solution to file (for plotting):
std::ofstream out("sol.dat");
dump (out, u, n, 0.0, dt);
out.close();
delete [] u;
// free array memory
return 0;
// success of execution
}
Command-Line Arguments
In this main program we get input data, such as tstop and dt , from the command
line. All command-line arguments in C and C CC programs are transferred to the
main function as an array of strings. For example, if the name of the executable file
is ode and we run
unix> ./ode 4.0 0.04
there are two command-line arguments: 4.0 and 0.04 . These arguments are stored
in an array of strings argv . This array has the name of the program (here ode ) as its
first argument ( argv[0] ). The first command-line argument is argv[1] , the second
is argv[2] , and so on. Observe that all command-line arguments are available as
strings, so if we want to compute with tstop , we need to convert the string to a
floating-point number. This is performed by the atof (ASCII to float) function.
The number of array elements in argv is provided as argc . We can thus test if the
user has provided a sufficient number of arguments (two in this case). The handling
of command-line arguments in C and C CC is reflected in many other languages,
including Java and Python.
Search WWH ::




Custom Search