Brief Specifications:
Class Song
Data members: Title(string), Artist(string), Length(Time, an object).
NB: length is the length of the song. It takes a time object (hh:mm:ss)but when saving to file, time should be saved as an int converted to seconds. This is my code so far
// song.h
#include "time.h" // contains data for time management
#include <string> // std::string
#define DELIM '|'
class Song
{
private:
// Data members
string title;
string artist;
Time length;
public:
// constructors
Song();
Song(string pTitle, string pArtist, Time pLength);
// destructor
~Song();
// member functions
void setTitle(string pTitle) {title = pTitle;}
void setArtist(string pArtist){artist = pArtist;}
void setLength(Time pLength) {length = pLength;}
string getTitle ()const { return title; }
string getArtist ()const { return artist; }
Time getLength()const { return length; }
};
// overloading input and output operators
ostream &operator<<(ostream &os, const Song &song);
istream &operator >> (istream &is, Song &song);
// in song.cpp
// overloading the << for saving a Song object to file
ostream & operator<<(ostream & os, const Song & song)
{
int len = song.getLength().getHour() * 3600 +
song.getLength().getMinutes() * 60 +
song.getLength().getSeconds();
os << song.getTitle() << DELIM;
os << song.getArtist() << DELIM;
os << len;
return os;
}
// This is where my problem is
// overloading the >> operator for input stream and reading from file
istream & operator >> (istream & is, Song & song)
{
string str;
Time t;
int total;
getline(is, str, DELIM);
song.setTitle(str);
getline(is, str, DELIM);
song.setArtist(str);
is >> total;
is.get();
// Reconvert this int to time
int tmpHr = total / 3600; // this extracts the hours correctly
int tmpMin = (total % 3600) * 60; // trying to get the minutes
int tmpSec = (total % 3600) % 60; // trying to get the seconds
t.setHour(tmpHr);
t.setMinutes(tmpMin);
t.setSeconds(tmpSec);
song.setLength(t);
return is;
}
// time.h
class Time
{
private:
// data members
int hours;
int minutes;
int seconds;
I have a test function to show song(to check whether i have extracted time correctly)
What I'd recommend you is to use chrono. Chrono is basically time.h for C++, but it has more functionalities and personally I see no reason to use time.h instead. Chrono has a duration cast that can be used to extract hours/mins/secs fairly easily.