C++流之间的区别是 false 和 eof()
C++ difference between stream is false and eof()
string tmp("f 1/2/3 4/5/6 7/8/9");
istringstream stin(tmp);
string token;
char ch;
int a,b,c,e;
stin >> token;
while(stin){
stin >> a >> ch >> b >> ch >>c;
cout <<a << " "<<b <<" "<<c << endl;
}
为什么输出是1 2 34 5 67 8 97 8 9但是为什么要将while(stin)更改为while(!stin.eof())输出为
- 1 2 34 5 67 8 9
和while(!stin.eof()有什么区别呢?多谢!
原因是在打印出变量之前,您没有检查读取是否成功。eof()
检查会更早地停止读取(因为它到达std::istringstream
末尾),但包含自己的微妙错误:
请参阅:为什么循环条件中的iostream::eof被认为是错误的?
例如,尝试在输入的末尾添加一个空格:"f 1/2/3 4/5/6 7/8/9 "
,您将获得相同的重复输出,并带有eof()
检查。
理想的解决方案可能是这样的:
int main()
{
istringstream stin("f 1/2/3 4/5/6 7/8/9");
string token;
char ch;
int a, b, c;
stin >> token;
while(stin >> a >> ch >> b >> ch >> c) // only loop on successful read
{
cout << a << " " << b << " " << c << endl;
}
}
相关文章:
- 为什么"do while"循环不断退出,即使条件计算结果为 false?
- 如何确定我已使用非编码文件到达 EOF?
- 伪造事实↔false
- QueryWorkingSet总是返回false
- 如何区分地图中的 0 和 false?
- 模板参数列表中的 false 在模板初始化期间计算为什么?
- std::ifstream::read 不会读取所有 512 字节,并设置 EOF 和失败位
- Arduino-C++ bool 不会从 false 变为 true
- 当返回类型声明为 ListNode 时,我们是否可以返回 false<T>*
- 而(!inputfile.eof())只读取第一行?
- EOF有更安全的替代方案吗?它在我的情况下不起作用
- "错误 C0000:语法错误,令牌"<EOF>"处出现意外$end,并且不确定
- 当我的 if 条件计算结果为 false 时,我的 else 块将不会执行
- 等于在 c++ 中返回 false
- 如何在 EOF 之前从文件中读取并将其放入字符串中?
- strcmp 对于相等的字符序列返回 false
- 如何在从文件中读取整数时使用 file.eof()?
- std::is_class 在引用类上为 false
- ios_base::sync_with_stdio(false); cin.tie(NULL);
- C++流之间的区别是 false 和 eof()