Trouble with fstream
Dec 3, 2012 at 10:53pm UTC
I'm trying to pull up a file called "test" to just run some temperatures through a program. The file is just numbers. The file should stop being read when it encounters a -1. I wrote the program around the lack of ability to pull up the file but hopefully I won't have to rewrite it from scratch. Code is as follows:
EDIT: found error in code so it actually reads the file now... I think. However it just prints all counters as 0 and the average temp is -1#J which I'm guessing isn't accurate.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
using namespace std;
int tempfunction (int );
double average (int );
void main()
{
ifstream inFile; ofstream outFile;
int temp, addtemp = 0, cnt = 0, coldcnt = 0, pleasentcnt = 0, hotcnt = 0; string fName;
cout << "Enter file name: " ; cin >> fName;
inFile.open(fName + ".txt" );
if (!inFile.fail())
{
cout << endl << "Temperature data:" << endl << endl;
while (!(tempfunction (temp) == -1))
{
cnt++;
inFile >> temp;
cout << right << setw (3) << cnt << " " << right << temp << " - " ;
if (tempfunction (temp) == 1)
{
cout << "COLD" << endl;
coldcnt++;
}
else if (tempfunction (temp) == 2)
{
cout << "PLEASENT" << endl;
pleasentcnt++;
}
else
{
cout << "HOT" << endl;
hotcnt++;
}
addtemp += temp;
}
}
inFile.close();
cout << endl << "Counters:" << endl;
cout << " Hot: " << hotcnt << " Pleasent: " << pleasentcnt << " Cold: " << coldcnt << endl << endl;
cout << " Average temp = " << fixed << setprecision(2) << double (addtemp) / cnt << endl;
}
int tempfunction (int temp)
{
if (temp == -1)
return 0;
else if (temp < 60)
return 1;
else if (60 <= temp && temp <=84)
return 2;
else
return 3;
}
Last edited on Dec 3, 2012 at 11:08pm UTC
Dec 4, 2012 at 3:46pm UTC
line 21 should be
while ((tempfunction (temp) != 0))
Last edited on Dec 4, 2012 at 3:57pm UTC
Topic archived. No new replies allowed.