In: Computer Science
Can anyone just check my code and tell me why the program doesn't show the end date & stops at the date before the end date? Tell me how i can fix it.
Question:
Write a program compare.cpp that asks the user to input two dates (the beginning and the end of the interval). The program should check each day in the interval and report which basin had higher elevation on that day by printing “East” or “West”, or print “Equal” if both basins are at the same level.
My code:
#include
#include
#include
#include
using namespace std;
int main()
{
string date;
string starting_date;
string ending_date;
double eastSt;
double eastEl;
double westSt;
double westEl;
int dateRange=0;
cout<< "Enter the starting date" << endl;
cin>> starting_date;
cout<< "Enter the ending date" << endl;
cin>> ending_date;
ifstream fin("Current_Reservoir_Levels.tsv");
if (fin.fail())
{
cerr << "File cannot be opened for reading." << endl;
exit(1);
}
string junk;
getline(fin, junk);
while(fin >> date >> eastSt >> eastEl >> westSt >> westEl)
{
fin.ignore(INT_MAX, '\n');
if (date == starting_date)
{
dateRange = 1;
}
if (date == ending_date)
{
dateRange= 0;
}
if (dateRange == 1)
{
if(eastEl > westEl)
{
cout<< date << " "<< "East " <
}
else if (eastEl < westEl)
{
cout<< date << " " << "West" <
}
else if (eastEl == westEl )
{
cout<< date << " " << "Equal" <
}
}
}
return 0;
}
Expected output
01/17/2018 West 01/18/2018 West 01/19/2018 West 01/20/2018 West 01/21/2018 West 01/22/2018 West 01/23/2018 West
Received output:
01/17/2018 West 01/18/2018 West 01/19/2018 West 01/20/2018 West 01/21/2018 West 01/22/2018 West
*************** F.H**************
Explanation
you are following like if start data came in file u r assigning dataRange=1 and if end date came u r making it as dataRange=0 but problem you need to make this is after complition of printing end date string also i have move below code after displaying result.
if (date == ending_date)
{
dateRange= 0;
}
//CODE TO COPY
#include<iostream>
#include<string>
#include <fstream>
#include <cstdlib>
using namespace std;
int main()
{
string date;
string starting_date;
string ending_date;
double eastSt;
double eastEl;
double westSt;
double westEl;
int dateRange=0;
cout<< "Enter the starting date" << endl;
cin>> starting_date;
cout<< "Enter the ending date" << endl;
cin>> ending_date;
ifstream fin("Current_Reservoir_Levels.tsv");
if (fin.fail())
{
cerr << "File cannot be opened for reading." << endl;
exit(1);
}
string junk;
getline(fin, junk);
while(fin >> date >> eastSt >> eastEl >> westSt >> westEl)
{
fin.ignore(INT_MAX, '\n');
if (date == starting_date)
{
dateRange = 1;
}
if (dateRange == 1)
{
if(eastEl > westEl)
{
cout<< date << " "<< "East " <<endl;
}
else if (eastEl < westEl)
{
cout<< date << " " << "West" <<endl;
}
else if (eastEl == westEl )
{
cout<< date << " " << "Equal" <<endl;
}
}
if (date == ending_date)
{
dateRange= 0;
}
}
return 0;
}