假设给定一个包含数字列表的非空文本文件,
1 2 3 4 5
我们用std::ifstream
将它们读入数字类型(int
,double
等)以及char
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
为什么会这样?
答案 0 :(得分:2)
读取EOF
时会得到int
,因为int
的流提取运算符会尝试读取直到找到空白或不适合int
的内容为止。因此,在读取了char
之后,它将尝试读取另一个5
,遇到文件末尾并且eofbit
被设置。
相反,char
的流提取运算符只会尝试读取一个char
,因此不会遇到文件结尾。尝试从文件中读取6个char
,您还将遇到EOF
。