Đoạn mã sau nên sao chép dữ liệu từ wifstream đến wcout. Sau khi nội dung được sao chép, chương trình sẽ ném ngoại lệ lỗi ios ::.Tại sao std :: copy (từ istream đến ostream) làm tăng ios :: failure exception?
#include <string>
#include <iostream>
#include <sstream>
#include <fstream>
#include <locale>
#include <iterator>
#include <algorithm>
int main(void)
{
std::locale::global(std::locale(""));
std::wifstream is;
is.exceptions(std::ios::failbit | std::ios::badbit);
is.open("test.ts", std::ios::binary);
is >> std::noskipws;
std::istream_iterator<wchar_t, wchar_t> in(is);
std::istream_iterator<wchar_t, wchar_t> end;
std::copy(in, end,
std::ostream_iterator<wchar_t, wchar_t>(std::wcout));
return 0;
}
Luồng chỉ nên ném ngoại lệ (xem mặt nạ ngoại lệ) nếu có gì xấu, nhưng không phải trên EOF.
dòng Setting trường hợp ngoại lệ có vẻ như là một ý tưởng tốt, nhưng nó thường không hoạt động như bạn mong đợi. Thay vào đó, chỉ cần kiểm tra trạng thái luồng trước khi sử dụng dữ liệu nhập, ví dụ: 'if (stream >> var) {/ * chỉ sử dụng var * /}'. –