- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
假设给定一个包含数字列表的非空文本文件,
1 2 3 4 5
然后我们用 std::ifstream
将它们读入数值类型(int
、double
等)以及 字符
int main()
{
ifstream fs {"textfile.txt"};
int val {0}; //read into ints
for (int i{0}; i < 5; ++i)
{
//read five times
fs >> val;
cout << val << " is read. Current state of file stream: "
<< bitset<3> (fs.rdstate()) << endl; //check stream state after each read
}
}
当读取为数字类型时,程序输出:
1 is read. Current state of fs: 000
2 is read. Current state of fs: 000
3 is read. Current state of fs: 000
4 is read. Current state of fs: 000
5 is read. Current state of fs: 010
在读取文件的最后一项时,设置了 eofbit。
但是读入 char
时不会发生同样的事情。
int main()
{
ifstream fs {"textfile.txt"};
char ch {0}; //read into chars
for (int i{0}; i < 5; ++i)
{
//read five times
fs >> ch;
cout << ch << " is read. Current state of file stream: "
<< bitset<3> (fs.rdstate()) << endl; //check stream state after each read
}
}
输出:
1 is read. Current state of fs: 000
2 is read. Current state of fs: 000
3 is read. Current state of fs: 000
4 is read. Current state of fs: 000
5 is read. Current state of fs: 000
为什么会这样?
最佳答案
读取 int
时得到 EOF
,因为 int
的流提取运算符会尝试读取,直到找到空格或不合适的内容对于 int
。因此它将在读取 5
后尝试读取另一个 char
,遇到文件末尾并且设置了 eofbit
。
相比之下,char
的流提取运算符只会尝试读取一个 char
,因此它不会遇到文件末尾。尝试从文件中读取 6 个 char
,您也会遇到 EOF
。
关于c++ - std::ifstream 在读取文件中的最后一项时设置 eofbit,但它仅在读取数字类型时发生,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52563223/
这段代码永远循环: #include #include #include int main(int argc, char *argv[]) { std::ifstream f(argv[
假设给定一个包含数字列表的非空文本文件, 1 2 3 4 5 然后我们用 std::ifstream 将它们读入数值类型(int、double 等)以及 字符 int main() { ifs
#include #include using namespace std; int main() { fstream file("out.txt", ios_base::app);
编辑:我原来的测试程序代码中有一个细微的错误:" char=" #include using namespace std; void info( int aRelativePos, istream
我想知道为什么 istream::get 将 failbit 和 eofbit 设置在一起。 std::getline 的行为不同:它在遇到文件末尾时设置 eofbit,在您尝试读取文件末尾时设置 f
考虑以下代码: ifstream in; try { in.exceptions ( ifstream::failbit | ifstream::badbit );
我正在尝试阅读尽可能多的 std::complex尽可能从文件(或任何 std::istream )。如果操作失败,我会检查 ios::eof()。如果没有设置,我就假设解析数据有错误,我可以向用户报
我是一名优秀的程序员,十分优秀!