我编写了一个按其速度分级的程序,并且即使从文件中读取输入(而不是手动插入),我也通常认为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
。从标准输入读取数据。
该行上剩余的输入数字多于UINT_MAX
你想用
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::numeric_limits<std::streamsize>::max()
是指示ignore
不计算字符的特殊值。即使您的行长于该行(除非您在烤面包机上运行,否则这几乎是不可能的),所有行都将被跳过。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句