Many simulation programs require a lengthy input file of constants. It is cumbersome to synchronize the order of the input values with the variables in the read statements as a program is being developed or modified. Fortran provides a namelist facility that works like this: The program
real x,y,zallows you to input the data values as
namelist/mydata/ x,y,z
read(5,mydata)
&mydata y = 3, x = -1, z = 2/where the variables x, y, and z may appear in any order. The value of each input variable is specified by its name.
The goal of this exercise is to implement an analogous facility in C++. Write a pair of C++ functions, read_data and present, as follows. read_data reads input of the form
pi 3.14159where the first string in each line is the name of a quantity and the second is its numerical value. The data is placed into an associative array (map) consisting of (string, double) pairs. Once you've read in the data, you can extract the values by name with a construct like:
e 2.71828
xyz -1.46e-03
etc.,
map<string,double> mydata;
read_data(cin, mydata);
double xyz = mydata["xyz"];
Implement read_data so that it can read from an arbitrary input stream, specified as the first argument. read_data should append new (name,value) pairs to the input map, which is specified as its second argument. (In this way, one map can be used to concatenate the data from multiple input files, if desired.) Your code can look like
#include <iostream>If a given key appears more than once in the input, then only the last value associated with the key is stored in the map.
#include <map>
using namespace std;
void read_data(istream& in, map<string,double>& input)
...
Also implement a function,
bool present(const map<string,double>& input, const string& key)that returns true if key is present in input and false otherwise. (present must never add new keys to the input, just check whether they are there. The const declarations emphasize that present doesn't alter its arguments.)
Turn in a printout in lab on Tuesday, Nov. 20, containing your two functions.
Copyright(c) 2007 by Eric J. Kostelich. All rights reserved.