Write a C++ program that reads a series of 12 temperatures (floating-point numbers) from an input file. It should prompt the user for the name of the input file. The input file should be place in the same directory where your source program resides. It should write out on the screen each temperature and the difference between the current temperature and the one preceding it. The difference is not output for the first temperature that is input. At the end of the program, the average temperature should be displayed to the 4th place after the decimal point. For example, given the following input data:
34.5 38.6 42.4 46.8 51.3 63.1 60.2 55.9 60.3 56.7 50.3 42.2
The output on the screen should be:

Please enter the input file name: XXXXX
The 12 temperatures read from file XXXXX is:
34.5
38.6 4.1
42.4 3.8
46.8 4.4
51.3 4.5
63.1 11.8
60.2 -2.9
55.9 -4.3
60.3 4.4
56.7 -3.6
50.3 -6.4
42.2 -8.1
The average temperature is: 50.1917

Input File:

#include <fstream>
using namespace std;

int main()
{
ofstream SaveFile("temp.txt");
SaveFile << "34.5 38.6 42.4 46.8 51.3 63.1 60.2 55.9 60.3 56.7 50.3 42.2";
SaveFile.close();
return 0;
}

My code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
	string line;
	

	ifstream openFile("temp.txt");
		if(openFile.is_open())
		{
			while(!openFile.eof());
			{
				getline (openFile,line);
				cout<<line<<endl;
			}
		openFile.close();
	}
	else 
		cout <<"Unable to open file";
	return 0;
}

I don't know why my code does not read my file. I need some real quick help. Please let me know where am I going wrong?

Thank you

Recommended Answers

All 2 Replies

do not use eof();

Do this instead.

while(getline (openFile,line) != NULL);
{
	cout<<line<<endl;
}

Chris

or if you wish to read the data items one at a time

ifstream openFile( "Data.txt" );
float temp;
while( openFile >> temp )
{
   ...
}

When you write

openFile >> temp

the return value of the input statement is the class object from which you are reading - openFile in this case. When the end-of-file is reached, the truth condition of the class object evaluates to false so the while loop will terminate.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.