字符串为空仍然给出 True 值
String being empty still gives True value
该代码用于使用二叉堆实现最大堆,输出为 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);
}
文件的输入值为:
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())
returns文件结束后为真值。我尝试用 `(line != "\n") 替换它,但错误仍然存在。错误的原因可能是什么?
回应“他们做同样的事情”的评论。不完全的。如果 getline 失败,则字符串保持不变(在本例中)。
#include <string>
#include <fstream>
#include <iostream>
int main(int, char**)
{
std::ifstream is("some invalid file name"); // nonsense
std::string s = "Hello World"; // any value will do
std::getline(is, s);
std::cout << "s = " << s << '\n';
return 0;
}
这应该打印 s = Hello World
。我认为一般规则是,一旦流失败,所有赌注都将取消。因此,评论者推荐的方法是在每次操作后检查流状态。
该代码用于使用二叉堆实现最大堆,输出为 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);
}
文件的输入值为:
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())
returns文件结束后为真值。我尝试用 `(line != "\n") 替换它,但错误仍然存在。错误的原因可能是什么?
回应“他们做同样的事情”的评论。不完全的。如果 getline 失败,则字符串保持不变(在本例中)。
#include <string>
#include <fstream>
#include <iostream>
int main(int, char**)
{
std::ifstream is("some invalid file name"); // nonsense
std::string s = "Hello World"; // any value will do
std::getline(is, s);
std::cout << "s = " << s << '\n';
return 0;
}
这应该打印 s = Hello World
。我认为一般规则是,一旦流失败,所有赌注都将取消。因此,评论者推荐的方法是在每次操作后检查流状态。