Outputting information to .dat file?

I've created a very basic program, that instructs a user to enter information (12 temperature values) and that gives an average temperature based on that information. When I build it, and run it, it works. As far as what the user sees on the monitor in the command prompt, this is all that should appear. However, I am also asked to output the temperature inputs to a .dat file, so they are recorded to a separate file, and also in that file, the differences between the 2nd and 1st input, 3rd and 2nd input, 4th and 3rd, ... (and so on)..., up to the 12th and 11th input. I am totally clueless as to how I should go about doing this. Anybody have any suggestions? This is my code so far:

#include <iostream>
#include <string>
#include <iomanip>

using namespace std;


int main()
{
float Temp1;
float Temp2;
float Temp3;
float Temp4;
float Temp5;
float Temp6;
float Temp7;
float Temp8;
float Temp9;
float Temp10;
float Temp11;
float Temp12;

cout << "Please enter a temperature: ";
cin >> Temp1;
cout << "Please enter a temperature: ";
cin >> Temp2;
cout << "Please enter a temperature: ";
cin >> Temp3;
cout << "Please enter a temperature: ";
cin >> Temp4;
cout << "Please enter a temperature: ";
cin >> Temp5;
cout << "Please enter a temperature: ";
cin >> Temp6;
cout << "Please enter a temperature: ";
cin >> Temp7;
cout << "Please enter a temperature: ";
cin >> Temp8;
cout << "Please enter a temperature: ";
cin >> Temp9;
cout << "Please enter a temperature: ";
cin >> Temp10;
cout << "Please enter a temperature: ";
cin >> Temp11;
cout << "Please enter a temperature: ";
cin >> Temp12;
cout << "The average temperature is: ";
cout <<((Temp1+Temp2+Temp3+Temp4+Temp5+Temp6+Temp7+Temp8+Temp9+Temp10+Temp11+Temp12)/12);
cout << "\n";
}
http://cplusplus.com/doc/tutorial/files/

when opening the file it's best to put at LEAST 1 check in to make sure the file opened properly.
and you should also make sure to close it if you have any other streams that could be trying to access.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <string>
#include <fstream>

using namespace std;

int main()
{
   ofstream outFile("something.dat"); // outFile is just a variable name for the object.
   
   if (! outFile.is_open)
   {
      cout << "Error: error opening output file: " << "something.dat" << endl;
      return 1;  // note: we return 1 to indicate exit status was failure.
   }
   // else we can process as needed

   // just like any output stream you use the << operators.
   outFile << ((Temp1+Temp2+Temp3+Temp4+Temp5+Temp6+Temp7+Temp8+Temp9+Temp10+Temp11+Temp12)/12);

   outFile.close();
   return 0;
}
Last edited on
Topic archived. No new replies allowed.