Reputation: 31
I have a problem with my code, the code runs but all of the numbers are everywhere.
RainfallToDate.txt :
0.01
1.74
0.19
0.65
0.50
0.10
0.00
0.02
0.01
0.06
1.57
7.76
averageRainfall.txt:
2.99
3.32
2.04
1.06
0.39
0.09
0.00
0.00
0.23
0.78
1.88
2.12
Here is the code:
#include <iostream> // for cout
#include <fstream> // for file I/O
#include <cstdlib> // for exit()
using namespace std;
int main()
{
ifstream fin;
ofstream fout;
ifstream fin_rainFall("rainfallToDate.txt");
ifstream fin_average("averageRainfall.txt");
if (fin.fail())
{
cout << "Input file failed to open.\n";
exit(-1);
}
fout.open("rainfall.txt");
if (fout.fail())
{
cout << "Output file failed to open.\n";
exit(-1);
}
fout << "Rainfall for Cupertino: A Comparison\n" << endl;
fout << "Month\tAverage\t 2015\tDeficit\n" << endl;
for (int i = 1 ; i <= 12 ;i++) { // counts the month from 1-12
char num[256];
char num2[256];
fout<< i << "\t";
fin_average.getline(num,256);
fout<<num << "\t";
fin_rainFall.getline(num2,220);
fout<<num2<< "\t";
double a;
double b;
while (fin_average >> a && fin_rainFall >> b){
fout <<"\t" << (a-b) << endl;
}
}
fin.close();
fout.close();
return 0;
}
I know where my problem is at, and it is at
double a;
double b;
while (fin_average >> a && fin_rainFall >> b){
fout <<"\t" << (a-b) << endl;
}
once I remove this line of code the code runs perfectly but I need this line so that I can subtract the average to the rainfall. Here is a picture of what I am getting.
Picture of what I am getting -
Picture of what I am supposed to have -
I have been working on trying to figure out how to fix this for the past hours and I have yet to figure out what is wrong.
More details: Pretty much my cost is supposed to print out data from two separate "text files" essentially merging them together into a third text file called rainfall.txt, and in there they are to subtract one and another to get the deficit.
Upvotes: 3
Views: 124
Reputation: 20980
The loop should be:
for (int i = 1 ; i <= 12 ;i++) { // counts the month from 1-12
double a;
double b;
fin_average >> a;
fin_rainFall >> b;
fout << i << "\t" <<a <<"\t" << b << "\t" << (a-b) << endl;
}
Upvotes: 1