【问题标题】:How to ignore the rest of the line?如何忽略该行的其余部分?
【发布时间】:2020-09-18 09:48:53
【问题描述】:

我编写了一个按速度分级的程序,我假设即使从文件中读取输入(而不是手动插入),I/O 通常也是瓶颈。在某些情况下,程序不需要当前行的全部输入,而应该继续读取下一行输入。

我发现std::cin.ignore(UINT_MAX, '\n') 作为一个选项。但是,假设性地,如果剩下的行还有更多字符呢?我怎么能直接丢弃该行的其余部分?


对于那些希望了解更多细节和示例的人:

#include <iostream>
#include <climits>
#include <iomanip>
#include <algorithm>
typedef unsigned int uint_t;

int main () {
    std::ios_base::sync_with_stdio(false);

    int t; std::cin >> t;

    for (int testcase = 0; testcase < t; testcase ++){
        // num entries in the next line
        unsigned int n; std::cin >> n;

        for(uint_t q=0; q<n; q++){
            uint_t height; std::cin >> height;
            if (height < 3){
                // do something
                std::cout << "Considering " << height << '\n';
            } else {
                // stop, finish reading line, then do next test case
                std::cin.ignore(UINT_MAX, '\n');
                break;
            }
        }
        std::cout << "Finished testcase " << testcase << std::endl;
    }
    return 0;
}

输入文件示例:

root@41d06f89ab19:/code# cat exmpl.in
2
4
1 2 3 4
6
1 2 3 4 5 6

这个示例文件当然效果很好:

root@41d06f89ab19:/code# ./exmpl.exe <exmpl.in
Considering 1
Considering 2
Finished testcase 0
Considering 1
Considering 2
Finished testcase 1

但是假设我在该行上剩余的输入数字比UINT_MAX 多。为了方便演示,假设UINT_MAX1(在代码中替换):

./exmpl.exe <exmpl.in
Considering 1
Considering 2
Finished testcase 0
Finished testcase 1

在这种情况下,第三行中的数字4 仍然存在,并在第二次测试用例运行中被读取为第一个数字。我想知道如何忽略在线上任何数量的剩余数字,即使它们超过UINT_MAX。从标准输入读取数据。

【问题讨论】:

  • 如何读取文件中的行?
  • @darclader 来自标准输入。我已经编辑了我的问题
  • @lucidbrot 显然你的问题不够清楚,因为所有 cmets 都要求澄清。现在清楚多了。
  • 有一个答案(现已删除),其中包含正确的方法(但建议不要使用它来支持不好的解决方案)。无论如何,std::numeric_limits&lt;std::streamsize&gt;::max() 是最大值,流中不能有更多字符
  • @Jabberwocky 恕我直言,它给出的建议很糟糕。正确的解决方案也在那里,我只是想知道为什么答案建议不要使用它。虽然可能取消删除并应用一个小修复将是最好的

标签: c++


【解决方案1】:

该行上剩余的输入数字多于 UINT_MAX

你想用

cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

std::numeric_limits&lt;std::streamsize&gt;::max() 是一个特殊值,它指示ignore 不计算字符数。即使您的线路比这更长(这不太可能,除非您在烤面包机上运行),所有这些都将被跳过。

【讨论】:

    猜你喜欢
    • 2010-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多