我编写了一个按其速度分级的程序,并且即使输入是从文件中读取(而不是手动插入)的,我也认为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_MAX
是1
(在代码中已替换):
./exmpl.exe <exmpl.in
Considering 1
Considering 2
Finished testcase 0
Finished testcase 1
在这种情况下,第三行中的数字4
保留下来,并在第二个测试用例运行中被读取为第一个数字。我想知道如何忽略该行上的任意数量的剩余数字,即使它们大于UINT_MAX
。从标准输入读取数据。
答案 0 :(得分:2)
该行上剩余的输入数字多于UINT_MAX
您要使用
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::numeric_limits<std::streamsize>::max()
是一个特殊值,它指示ignore
不对字符进行计数。即使您的线路长于线路长度(除非您在烤面包机上运行,否则这几乎是不可能的),所有线路都将被跳过。