gpt4 book ai didi

C++ iStream、If-Else 和 vector

转载 作者:行者123 更新时间:2023-11-28 07:50:48 25 4
gpt4 key购买 nike

我有这个 iStream 函数可以读取格式为 .txt 的数据文件:

  Pink Floyd: Dark Side of the Moon
0:01:30 - Speak to Me

我的功能几乎完美运行。

以下是我无法解决的问题。1) 它打印(输出)每首轨道被添加到专辑中(因此打印第一个专辑的 x 个拷贝,每个拷贝都附有下一首轨道。2) 创建新专辑时,它会保留上一张专辑中的旧轨道,并继续逐一添加。 (因此最终专辑包含所有专辑中的每首轨道)

显然我希望每张专辑只打印一次,并且每张专辑只有自己的歌曲...任何帮助将不胜感激。谢谢。

最佳答案

我发现你的代码有很多问题。

stringstream stringstreamFirst(line);

您没有使用变量 stringstreamFirst,此时 line 为空。

Album anAlbum(artistName,albumTitle,trackVector);

这条线有很多问题。

  • 它使用了错误的值。
    第一行中,artistNamealbumTitleTrackVector 都是空的。当您最终遇到一张新专辑时,artistNamealbumTitleTrackVector 是上一张专辑的,而不是当前专辑的。当您到达专辑中的轨道时,这些值是正确的——但那不是您想要创建新专辑对象的时候。
  • 放错地方了。
    正如放置的那样,此语句为输入文件中的每一行创建一个 Album 对象。创建新相册对象的正确位置是当您在输入文件中遇到新相册条目时。

stringstream stringstreamNew(line);
stringstream stringstreamNewNew(line);

为什么名称复杂,为什么需要两个变量?另一种方法是只使用一个 stringstream,创建为 while 循环的第一行。

if (!(line[8] == '-'))
else if (line[8] == '-')

不要像这样复制您的 bool 条件。如果您的意思是 else(这就是您的意思),只需使用 else。该行是专辑条目或轨道条目;没有别的了。

else // These lines are missing

您没有任何错误处理。如果您无法解析什么可能应该是专辑条目,或者什么可能应该是轨道条目怎么办?

你需要做什么(伪代码):

while (getline(istr, line)) {
stringstream linestream (line);
if (line looks like an album line) {
if (not the first line in the file) {
// Create an album using the artist name, album title, and track vector
// and add this album onto the vector of albums
}
// Parse the line for artist name and album title, preferably handling errors
// Clear the trackVector that now pertains to the previous album
}
else {
// Parse the line for track duration and name, preferably handling errors
// Add the track to the track vector.
}
}
// Create an album to cover the last album plus set of tracks

关于C++ iStream、If-Else 和 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13820729/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com