Skip to main content

Section 11.10 Case Study: Temperature Ranges

We have a long list of weather data for a number of US cities in a datafile. Each line of the contains:
Data: Temps.txt
Albany	NY	22.2	71.1	38.6
Albuquerque	NM	35.7	78.5	9.47
Anchorage	AK	15.8	58.4	16.08
Atlanta	GA	42.7	80	50.2
Austin	TX	50.2	84.2	33.65
Baltimore	MD	32.3	76.5	41.94
Boise	ID	30.2	74.7	12.19
Chicago	IL	22	73.3	36.27
Dallas	TX	44.1	85	34.73
Denver	CO	29.2	73.4	15.81
Duluth	MN	8.4	65.5	31
Portland	OR	39.9	68.1	37.07
We would like to read the file, for each city print out the range of temperatures seen, and find the one city with the largest difference between the average January and July temperatures.

Subsection 11.10.1 Understanding the problem

We can break this problem into a few key parts:
  • Read the file
  • For each city, calculate the range of temperatures
  • Figuring out which city has the largest differential
The second part depends on having data to work with, and the third part depends on the second part, so we will need to tackle them in order.
We don’t need to store the data for very long. As we read each line, we can calculate the temperature range for that city and decide β€œis this a bigger difference than I have seen so far?”. If so, we will remember this new city.

Subsection 11.10.2 Reading Data

Our data looks like it should be easy to read using >>. Every piece of data is separated by whitespace and each line has exactly the same number of tokens. (If some of the cities had two word names like San Francisco that would make things much harder!)
Rather than trying to read all the data at once, let’s just try to read the first line. There isn’t an easy way to β€œskip” tokens in a text file. We have to read all the data in the file, even if we don’t care about what is there. So on each line, we need to read all five pieces of data. Here is an attempt to do that for just the first line:
Listing 11.10.1.
Next up, we can loop to read and print all of the data. Complete the logic for doing so:

Subsection 11.10.3 Calculating Differences

Now let’s calculate the temperature range for each city. We can do this by subtracting the average January temperature from the average July temperature. For now, we will just print out those values, along with the two temperatures.
Listing 11.10.2.

Subsection 11.10.4 Finding the Max

Now we can worry about identifying which town has the largest difference. To do this, we need to keep track of two pieces of information: which town has the biggest difference so far (a string) and what that difference is (a double). Each time we see a new city, we will check to see if it’s difference is greater than the max difference we have seen. If so, we will update both values.

Checkpoint 11.10.1.

Construct the algorithm to find the largest difference. Assume inFile is already open.
You have attempted of activities on this page.