Hello all! I am new around here (as of about 5 minutes ago). My name is Jeremy and I am a 27 year-old Marine who is currently attending UC Denver for computer science. I am in my first C++ class and I have to say, I LOVE it. I am, however, a little confused right now, which brings me to my question(s):
I have an assignment in class that asks the following:
"Write a program that will read in a file named pa7-temp.txt (located in the current directory) that contains a set of temperatures, and then prints out how many were in the file and the average temperature. This program must read the input data in one line at a time as strings.
The output should look like this (with XX and YY.YYYY being replaced with correct numbers):
There were XX days of temperature data and the average temperature was YY.YYYY."
I have started putting this whole thing together in my terminal (using dino-macbook pro running OSX 10.5.8) and I am lost. This is what I have so far... I have no idea where to go from here:
I have included <iomanip> in order to set the precision of my average temp result. Please note: I AM NOT ASKING FOR YOU TO WRITE THIS. I need to learn this stuff. My question is, since my instructor wants each line of the txt file input as a string, is using a char array proper? Also, every line in the txt file is a double digit number. I would love to just store the info in an integer array and then do some siimple math and be done, but that's not what it's asking me to do. I'm not sure how to store all numbers into a single "bin" and then convert the strings to something I can add (read: integers). This is my first issue.
Any advice would be greatly appreciated. Thanks!
P.S. Here are the contents of the txt file I'm using. It's under file name "pa7-temp.txt".
If you know that the file will contain numbers, I would simply create a variable that holds the current sum. Then you can do something like:
while( inputFile >> currentTemp )
The above approach is safer for reading files than using eof(). It will read the file and each number it finds will get placed into currentTemp during each iteration of the loop. I would use use a double for the sum value and currentTemp value. You'll also need a counter variable to hold how many temperatures there were.
Thanks Alterah! I'll give this a go. The only question I have is, will storing the numbers into a variable, like you're suggesting, satisfy the requirement to read each line of the text file as a string?
Eh, strictly speaking, it won't. What you can do is use getline and string variable. Then you can use atoi() to convert the string to an integer. You'll need to convert the string to a C-style string when using it with atoi(). Luckily the string class has a way to do this: