使用.eof()方法的无限循环
Infinite loop with .eof() method
我正试着做关于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
你能帮我一下吗?我确实尽力解决了,但仍然做不到:
非常感谢
问题出现在Album
的operator>>
中。该操作员尝试读取尽可能多的磁道,直到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
,以便在没有艺术家和/或相册可供阅读的情况下提前退出。
相关文章:
- 过载'operator new'如何导致无限循环?
- C++正则表达式无限循环
- 程序在尝试猜测它选择的随机数时进入无限循环?
- 遍历链表时的无限循环
- 循环链表:无限循环
- 比较两个字符串后卡在无限循环中
- 在做一段时间内检查字符的无限循环
- 逐字读取文本文件中的每一行并转换为 int(无限循环或崩溃?
- 在这个无限循环中,当输入 0 时终止,当输入 int 范围之外的任何内容时,程序行为不正常
- 可能的无限循环
- 超出 int 的值范围后的无限循环
- 为什么这段代码会导致无限循环?
- 运行无限循环的最小二叉树问题
- 在分配和发布递增循环迭代器时C++无限循环(gcc 错误?
- 为什么这种方法会进入无限循环?
- 可行的方法被困在无限循环中
- 使用.eof()方法的无限循环
- 确定空无限循环的编译器行为的最佳方法是什么?
- 使用或不使用join()方法与无限循环
- 有什么更有效的方法来确保我不会在这个快速排序函数中陷入无限循环?(C++)