【问题标题】:How to look ahead multiple steps while reading files in C++如何在 C++ 中读取文件时向前看多个步骤
【发布时间】:2012-09-21 12:04:47
【问题描述】:

我有一个输入文件,其中包含多个由空格或换行符分隔的整数。 例如:

7\n
2 2\n
3 4\n
\n
8\n
3 1\n
5 6\n
7 7\n
\n
3\n
1 2\n
3 4\n

....等等。

我需要根据这个输入文件来决定我有多少个不同的输入集。我无法做到这一点。有什么建议吗?

【问题讨论】:

  • 每个输入集基本上用2个换行符分隔
  • 你只想统计输入集的数量吗?还是您打算将所有输入集读入某种数据结构?

标签: c++ file newline delimiter


【解决方案1】:

逐行读取文件。每次读取后,检查流中的下一个字符是什么。如果是 '\n'(或 EOF),则您位于输入集的末尾。

std::string line;
std::ifstream stream;
size_t sets = 0;

while (std::getline(stream, line)) {

    // do something with line

    int next = stream.get()
    if (next == '\n' || next == EOF)
        ++sets;
    else
        stream.putback(next);
}

【讨论】:

    猜你喜欢
    • 2015-01-09
    • 2015-04-09
    • 2014-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-12
    • 2023-04-03
    • 1970-01-01
    相关资源
    最近更新 更多