Предположим, задан непустой текстовый файл, содержащий список чисел
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
s не происходит то же самое.
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
Почему это так?