【问题标题】:How can i read a file until a specific line in c++我如何读取文件直到 C++ 中的特定行
【发布时间】:2020-08-15 06:15:15
【问题描述】:

我是编程新手。请帮我解决以下问题: 我有一个文件:Subtraction.txt

有如下字幕:简介,第 1 部分,第 2 部分,...

在第 1 部分之前是否有可能从文件中读取,显示文件的内容,然后继续从该位置读取等等? nooflines 可以忽略!

ifstream in("C:\\Users\\Nusrat\\Desktop\\Subtraction.txt");
if(!in) {
    cout << "Cannot open input file";
    return 1;
}

string line;
while(getline(in, line))
{
    cout<<line<<endl;
    nooflines += 1;
}

in.close();
cout<<nooflines<<endl;

【问题讨论】:

  • 如果你知道什么时候应该开始什么时候应该停止,只要写下条件来检测它。
  • 您已经知道如何从文件中读取和显示行。您需要做的就是查看这些行包含的内容并采取行动。 std::string 具有用于此目的的 operator==compare() 方法。例如:if (line.compare(0, 5, "Part ") == 0) { ... }istringstream iss(line); string word; iss &gt;&gt; word; if (word == "Part") { ... }

标签: c++ file codeblocks variable-assignment


【解决方案1】:

我已设法在给定行停止文件。但是我如何从我停止的地方开始呢?修改后的版本如下:

ifstream in("C:\\Users\\Nusrat\\Desktop\\Subtraction.txt");
         if(!in) {
            cout << "Cannot open input file";
            return 1;
        }

        string line;

        while(getline(in, line))
        {
            cout<<line<<endl;
            while(line == "Now it is your turn to work out exercises!")
            {
                continue;
            }

【讨论】:

    猜你喜欢
    • 2015-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多