从文件读取直到出现特定行,无法创建循环

时间:2018-12-11 19:34:42

标签: c++ file

我的输入文件是:

Title: Titanic
17:40 hall 1
19:20 hall 7
20:20 hall 1
Title: To Kill a Mockingbird
14:10 hall 3
15:50 hall 3
18:25 hall 8
20:30 hall 2
Title: The Silence of the Lambs
19:30 hall 5
20:50 hall 4
22:10 hall 3

我的代码:

const std::string filename = "schedule.txt";
std::string movieName, movieTime, movieHall;
std::ifstream file (filename);
if (file.is_open()) {
        getline(file, movieName);
        file >> movieTime >> movieHall; 
    file.close();
}
else
    std::cout << "unable to open file";

我不知道如何创建一个循环,该循环将为每个电影保存每个movieTime和movieHall,然后继续播放另一个电影及其movieTime / movieHall。我尝试使用find,但是该程序找到了第一个“标题”,然后将所有内容随机保存到时间和大厅,它不会停在另一个标题上,以便通过getline读取它。

编辑 解决了我的std::istringstream

问题
const std::string filename = "schedule.txt";
std::string movieName, movieTime, movieHall, read;
std::ifstream file (filename);

if (file.is_open()) {
    while(getline(file, read)){

        std::istringstream iss(read);
        std::string phrase;

        if( std::getline(iss, phrase, ' ') ){
            if(phrase == "Title")
            {
                std::cout << read << std::endl;
            }
            else
            {
                file >> movieTime >> movieHall;
                std::cout << movieTime << " " << movieHall << std::endl;
            }

        }
    }
    file.close();
}
else
    std::cout << "unable to open file";

再次感谢您@Fubert

1 个答案:

答案 0 :(得分:0)

尝试以下操作:标题以Title:开头,所以不要阅读整行-只需阅读第一个字符串,然后如果它是Title:将行的其余部分读入title。而且,如果不是标题:那么该是时候了,您可以保存它并将行中的其余内容读入大厅。

#include <iostream>
#include <fstream>

int main()
{
    const std::string filename = "schedule.txt";
    std::string test, movieName, movieTime, movieHall;
    std::ifstream file (filename);
    if (file.is_open()) {
        while (file >> test) {
            // At this point test is either "Title:" or a movie time
            if (test == "Title:") {
                // test is "Title:" so we need to save the movie title
                std::getline(file, movieName);
                std::cout << "\nMovie:" << movieName;
            } else {
                // test is a movie time so save that movie time and then read the movie hall
                movieTime = test;
                std::getline(file, movieHall);
                std::cout << ", " << movieTime << movieHall;
            }
        }
        file.close();
    }
    else
        std::cout << "unable to open file";

    return 0;
}

您可以在此处在线尝试: https://onlinegdb.com/By--4j6JV