使用.eof()方法的无限循环

Infinite loop with .eof() method

本文关键字:无限循环 方法 eof 使用      更新时间:2023-10-16

我正试着做关于Album项目的C++练习。基本上,我需要有4个类,即:持续时间、音轨(持续时间对象+音轨标题)、专辑(艺术家名称、专辑标题和我的音轨对象的集合)和专辑收藏(只有专辑对象的集合的集合)是可变的。

我通过分配键盘上的值或给定值来测试所有的类,它们都有效。然而,当我试图让他们在一个txt文件中阅读时。它只是在相册收藏应用程序中不断循环,从未停止。我知道我的问题出在>>运算符上,以及我是否对故障位做了错误的处理。然而,我真的不知道该怎么办才能解决这个问题。

这是我的>>操作员在持续时间对象中

inline std::istream& operator >> (std::istream& is, Duration& f)
{
char c;
int h,m,s;
if (is >> h >> c >> m >> c >> s){
if (c==':'){
f = Duration (h,m,s);
}
else{
is.clear(std::ios_base::failbit);
}
} else{
is.clear(std::ios_base::failbit);
}
return is;

}

这是我在跟踪对象中的>>操作员

istream& operator>>(istream& is, Track& t){
Duration duration;
char trackTitle[256];
char c1;
if (is>>duration>>c1){
is.getline(trackTitle,256);
t = Track(duration,trackTitle);
}
else{
is.clear(ios_base::failbit);
}
return is;

}

这是我在相册类中的>>操作员

istream& operator>>(istream& is, Album& album){
char artistName[256];
char albumTitle [256];
vector<Track> trackCollection;
Track track;

is.getline(artistName, 256, ':');
is.getline(albumTitle, 256);
while ((is>>track) && (!is.fail())){
trackCollection.push_back(track);
}
album = Album(artistName,albumTitle,trackCollection);
if (is.eof()){
is.clear(ios_base::failbit);
is.ignore(256,'n');
}
else{
is.clear();
}
return is;

}

这是我在AlbumCollection类中的>>操作员

std::istream& operator>>(std::istream& is,AlbumCollection& albumCollection){
Album album;
vector<Album>albums;
while (is>>album) {
albumCollection.addAlbum(album);
}
return is;

}

and the format of the input file .txt is: 
The Jimi Hendrix Experience: Are you Experienced? 
0:03:22 - Foxy Lady
0:03:32 - Highway Chile
Pink Floyd: Dark Side of the Moon
0:01:30 - Speak to Me
0:02:43 - Breathe

你能帮我一下吗?我确实尽力解决了,但仍然做不到:

非常感谢

问题出现在Albumoperator>>中。该操作员尝试读取尽可能多的磁道,直到Track operator>>发出读取失败的信号。然后,Album operator>>重置流的故障状态。通过不断重置流的故障状态,即使无法读取艺术家姓名或专辑标题,操作员也无法发出已用完所有专辑的信号。

由于存储在文件中时通常无法判断"X的集合"的结束位置,因此通常将预期数量的项目存储在实际项目之前。要做到这一点,您需要将文件格式更改为(例如):

2
The Jimi Hendrix Experience: Are you Experienced? 
2
0:03:22 - Foxy Lady
0:03:32 - Highway Chile
Pink Floyd: Dark Side of the Moon
2
0:01:30 - Speak to Me
0:02:43 - Breathe

如果不能更改文件格式,您也可以将operator>>更改为Album,以便在没有艺术家和/或相册可供阅读的情况下提前退出。