더북(TheBook)

파일 I/O의 예외는 부분적으로 오류를 방지한다. 예를 들어 다음은 분명히 잘못된 프로그램이다(타입이 일치하지 않고 숫자를 분리하지 않는다).

void with_io_exceptions(ios& io)
{
    io.exceptions(ios_base::badbit | ios_base::fallbit);
}

int main()
{
    std::ofstream outfile;
    with_io_exceptions(outfile);
    outfile.open("f.txt");
    double o1 = 5.2, o2 = 6.2;
    outfile << o1 << o2 << std::endl;    // 구분자 없음
    outfile.close();
    std::ifstream infile;
    with_io_exceptions(infile);
    infile.open("f.txt");
    int i1, i2;
    char c;
    infile >> i1 >> c >> i2;    // 타입 불일치
    std::cout << "i1 = " << i1 << ", i2 = " << i2 << ‘\n;
}

그럼에도 예외가 발생하지 않고 다음과 같은 출력 결과가 나온다.

i1 = 5, i2 = 26

신간 소식 구독하기
뉴스레터에 가입하시고 이메일로 신간 소식을 받아 보세요.