我有一个csv文件,其数据如下:9
我已经将日期读取的运算符(DD / MM / YY)和时间整数(HH:MM:SS)和PM作为char,Name和Genre作为字符串加载。这是我的代码:
在我的时间课程中:
03/10/2016 09:10:10 PM, Name, Genre
和我的日期类
istream & operator >> (istream & is, Time & time)
{
char colon;
is >> time.hour >> colon >> time.minute >> colon >> time.second >> time.PM;
return is;
}
我在另一个类中读取了我的文件:
istream & operator >> (istream & is, Date & date)
{
char slash;
is >> date.day >> slash >> date.month >> slash >> date.year;
return is;
}
所以基本上,正如你所看到的,我打印出了程序读入的内容以进行测试,这只是一个小问题:
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
}
为什么PM中的M被跳过并分配给名称?
答案 0 :(得分:3)
问题是这一行没有消耗足够多的字符:
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, Genre
。 getline()
调用从此开头读取到下一个逗号,将字符"M"
存储在Name
中。
要从流中删除完整字符串“PM”,您需要读取两个字符。一种方法是在最后读取并丢弃一个额外的字符。
is >> time.hour >> colon >> time.minute >> colon >> time.second >> time.PM >> colon;