ssskh12
ssskh12

Reputation: 23

overloaded operator reading from csv file

I have a csv file that has data like so: 03/10/2016 09:10:10 PM, Name, Genre

and I have loaded operators that read in the date as integers (DD/MM/YY) and time as integers (HH:MM:SS) and the PM as char, Name and Genre as strings. Here's my code:

In my Time class:

istream & operator >> (istream & is, Time & time)

{
    char colon;
    is >> time.hour >> colon >> time.minute >> colon >> time.second >> time.PM;

    return is;
}

and my Date class

    istream & operator >> (istream & is, Date & date)

{
    char slash;
    is >> date.day >> slash >> date.month >> slash >> date.year;
    return is;
}

I read in my file in another class like so:

string line; //declaration
Show show; //declaration

while (!inFile.eof())
{
    inFile >> date;

    cout << "Date = " << date.getDay() << "/" << date.getMonth() << "/" << date.getYear()<< endl;

    inFile >> time;

    cout << "Time = " << time.getHour() << ":" << time.getMinute() << ":" << time.getSecond() << " " << time.getPM() << " " << endl;


    getline(inFile, line, ',');
    show.setName(line);

    cout << "Name = " << line << endl;

    getline(inFile, line, ',');
    show.setGenre(line);

    cout << "Genre = " << line << endl;

    showVector.push_back(show) //pushback the objects into a vector<Show> showVector
}

So basically, as you can see, I printed out what the program reads in to test and there's just a small issue:

Date = 16/11/2004
Time = 9:30:20 P 
Name = M
Genre = House, Medical Drama

Why is the M in PM being skipped over and assigned to the Name?

Upvotes: 0

Views: 952

Answers (1)

Ryan Bemrose
Ryan Bemrose

Reputation: 9266

The problem is this line, which isn't consuming enough characters:

is >> time.hour >> colon >> time.minute >> colon >> time.second >> time.PM;

Before running the line, your input stream contains 09:10:10 PM, Name, Genre. The fields are then read as follows:

"09" >> time.hour (int)
":"  >> colon (char)
"10" >> time.minute (int)
":"  >> colon (char)
"10" >> time.second (int)
"P"  >> time.PM (char)

After reading these characters, the remaining stream is M, Name, Genre. The getline() call reads from the beginning of this to the next comma, storing the string "M" in Name.

In order to remove the full string "PM" from the stream, you need to read two characters. One way to do this is to read and discard one extra character at the end.

is >> time.hour >> colon >> time.minute >> colon >> time.second >> time.PM >> colon;

Upvotes: 3

Related Questions