从 csv 文件中读取的重载运算符

overloaded operator reading from csv file

我有一个包含如下数据的 csv 文件:03/10/2016 09:10:10 PM, Name, Genre

并且我加载了以整数形式读取日期 (DD/MM/YY) 和以整数形式读取时间 (HH:MM:SS) 以及以字符形式读取 PM、以字符串形式读取名称和流派的运算符。这是我的代码:

我的时代class:

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

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

    return is;
}

和我的约会对象class

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

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

我在另一个 class 中读取了我的文件,如下所示:

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
}

基本上,如您所见,我打印了程序读取的内容以进行测试,这只是一个小问题:

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

为什么 PM 中的 M 被跳过并分配给 Name?

问题出在这一行,它没有使用足够的字符:

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

在 运行 行之前,您的输入流包含 09:10:10 PM, Name, Genre。然后字段读取如下:

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

读完这些字符后,剩下的流是M, Name, Genregetline() 调用从 this 的开头读取到下一个逗号,将字符串 "M" 存储在 Name.

为了从流中删除完整的字符串 "PM",您需要读取两个字符。一种方法是读取并丢弃末尾的一个额外字符。

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