Using Assertions with Streams

Assertions are a convenient way for programmers to deal with error conditions; the Standard C++ library has a function called assert() that is used for this purpose.
#include <iostream.h>   // cin/cout
#include <fstream.h>    // ifstream
#include <assert.h>     // assert()

void main(void)
{
  ifstream inFile;

  inFile.open("myfile.in", ios::in);
 
  assert( !inFile.fail() );

  // process file
}
You can read the assertion as "make sure that this is true." So, the above assertion is testing to make sure that !inFile.fail() is TRUE; meaning that there is no failure. This is a sample of what happens when an assertion fails:
Assertion failed: !inFile.fail(), file PROGRAM6.CPP, line 11
Abnormal program termination
Use assertions when you want your program to halt immediately. (It's not very user-friendly, though)

Previous page
Next page

Back to Lesson 13 Index
Back to Outline