In-class exercise and homework for Tuesday, Nov. 6

Due Tuesday, Nov. 13.

Announcement

Next Tuesday, Nov. 20, will be an open lab period. You may use the time to complete any assignments that you have not yet finished, or you may work on any programming that you need to do for your project. I will not accept any late homework after Nov. 20.

Today's exercise

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,z
namelist/mydata/ x,y,z
read(5,mydata)
allows you to input the data values as
&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.14159
e    2.71828
xyz    -1.46e-03
etc.,
where 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:
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>
#include <map>

using namespace std;

void read_data(istream& in, map<string,double>& input)
...
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.

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.)

Reference

Here is a C++ reference site that you may find helpful (see in particular the link to C++ maps).

Sample program

Here is a sample C++ program that illustrates how to use setprecision to alter the number of significant digits on an output stream.

Submission instructions

Turn in a printout in lab on Tuesday, Nov. 20, containing your two functions.

Copyright(c) 2007 by Eric J. Kostelich. All rights reserved.