I am trying to make a program keeping track of average temperatures and rainfall. I have a text file with four integers per line (each line represents a day), and I want to read one line at a time and deal with each of the variables per day.
The problem is that I can't seem to read the file values into variables. When I print the variables to the screen, it just prints garbage. PS. In the code beneath, I try to deal with just the first line of the file. How can I read from every line, one at a time?
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string fileName = "metrolog.dta";
string buffer;
int numOfDays = 0,
dayNumber,
maxTemp,
minTemp,
rainfall,
tempDiff,
tempDiffMax,
totalMaxTemp,
totalMinTemp,
totalRainfall;
ifstream infile(fileName);
while(getline(infile, buffer))
if(!buffer.empty())
++numOfDays;
cout << "Number of entries: " << numOfDays << endl;
infile >> dayNumber >> minTemp >> maxTemp >> rainfall;
cout << dayNumber << " " << minTemp << " " << maxTemp << " " << rainfall << endl;
return 0;
}
The file looks like this:
1 9 12 23
2 8 9 20
3 7 13 18
4 8 10 15
5 7 13 10
6 6 9 8
7 5 8 12
8 4 10 6
9 3 9 12
10 4 7 6
The problem is
while(getline(infile, buffer))
if(!buffer.empty())
++numOfDays;
Reads until the end of the file. Then on your next read
infile >> dayNumber >> minTemp >> maxTemp >> rainfall;
Nothing happens since the eof
flag is set so
cout << dayNumber << " " << minTemp << " " << maxTemp << " " << rainfall << endl;
Prints out whatever garbage is in the variables since you do not initialize them to any particular variable. You need to reset the stream pointer back to the beginning of the file. You can do that with
infile.clear(); // clear error flags
infile.seekg(0, std::ios::beg); // set stream back to the beginning
Another way to do this would be to read the file and count the lines at the same time. You can do that with
while (infile >> dayNumber >> minTemp >> maxTemp >> rainfall)
{
++numOfDays;
cout << dayNumber << " " << minTemp << " " << maxTemp << " " << rainfall << endl;
}
But this will only work if you can print out the number of entries after the list.