I'm working on a university assignment to read in data from a file and could really use some help!
The data file contains weather data and looks like:
31/03/2016 9:00,14.6,175,17,0,1013.4,1016.9,1017,0,68.2,6,512,22.7,24.1,25.5
The assignment requires a class to read and store the date, time and all the int/double values. I have to use a date class to read the date, a time class to read the time and the WeatherData class brings it all together using overloaded stream operator.
I'm unit testing the WeatherData class (which will be used in an array of WeatherData classes) with a datafile that includes the date, time and just one double variable: 31/03/2016 9:00,14.6
The output I get is: 31/3/2016 0:0 0
I've unit tested the Date and Time classes and they work as expected. I can't see why it fails after the date. Any help would be greatly appreciated!
TestWeatherData.cpp
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <cstdlib>
#include "../Practice/date.h"
#include "../Practice/time.h"
#include "../Practice/weatherdata.h"
using namespace std;
istream & operator >>( istream & input, Date & D )
{
string temp;
string convertToInt;
int tempDay;
int tempMonth;
int tempYear;
getline(input, temp);
stringstream ss(temp);
getline(ss, convertToInt, '/');
tempDay = atoi(convertToInt.c_str());
D.SetDay(tempDay);
getline(ss, convertToInt, '/');
tempMonth = atoi(convertToInt.c_str());
D.SetMonth(tempMonth);
getline(ss, convertToInt);
tempYear = atoi(convertToInt.c_str());
D.SetYear(tempYear);
return input;
}
ostream & operator <<( ostream & os, const Date & D )
{
os << D.GetDay() << "/" << D.GetMonth()
<< "/" << D.GetYear();
return os;
}
istream & operator >>( istream & input, Time & T )
{
string temp;
string convertToInt;
int tempHours;
int tempMinutes;
getline(input, temp);
stringstream ss(temp);
getline(ss, convertToInt, ':');
tempHours = atoi(convertToInt.c_str());
T.SetHours(tempHours);
getline(ss, convertToInt);
tempMinutes = atoi(convertToInt.c_str());
T.SetMinutes(tempMinutes);
return input;
}
ostream & operator <<( ostream & os, const Time & T )
{
os << T.GetHours() << ":" << T.GetMinutes();
return os;
}
istream & operator >>( istream & input, WeatherData & W )
{
string temp;
string convertToDouble;
Date tempDate;
Time tempTime;
double tempDP;
input >> tempDate >> tempTime;
W.setDate(tempDate);
W.setTime(tempTime);
getline(input, temp);
stringstream ss(temp);
getline(ss, convertToDouble);
tempDP = atof(convertToDouble.c_str());
W.setDP(tempDP);
return input;
}
ostream & operator <<( ostream & os, const WeatherData & W )
{
os << W.getDate() << ' ' << W.getTime() << ' ' << W.getDP();
return os;
}
int main()
{
ifstream infile( "data.txt" );
if( !infile ) return -1;
WeatherData W;
infile >> W;
cout << W;
return 0;
}