【发布时间】:2021-06-23 23:53:25
【问题描述】:
该代码用于使用二进制堆实现 Max-Heaps,但输出却是 1000 条不需要的行。
auto input = ifstream(filename);
string line;
getline(input,line);
while(!line.empty())
{
int option;
int in;
stringstream l(line);
l >> in;
option = in;
switch (option)
{
case 0:
{
cout << getMax() << "\n";
break;
}
case 1:
{
while(l >> in)
{
insert(in);
}
break;
}
case 2:
{
cout << extractMax() << "\n";
break;
}
case 3:
{
filled = -1;
while(l >> in)
{
insert(in);
}
break;
}
}
getline(input,line);
}
File的输入值为:
1 6 2 8 12 3 7
0
2
2
0
1 11
0
3 5 15 12 7 9 13 35
2
2
2
调试时,while 条件(!line.empty()) 在文件结束后返回一个真值。我尝试用 `(line != "\n") 替换它,但错误仍然存在。错误的原因可能是什么?
【问题讨论】:
-
while(getline(input, line))-- 你为什么不做这么简单的事情?循环底部不需要getline。 -
是的,虽然
(getline(input, line))有效,但如果另一个原因相同,为什么会导致错误? -
@PaulMcKenzie 它必须是
while(getline(input, line)) { if(line.empty()) break; ...,但是是的,这样会更健壮。 -
与其猜测
line是什么,不如去检查一下? (您可以使用调试器或将其及其大小流式传输到std::cerr。)