< previous page page_268 next page >

Page 268
when an odd number is read. The counter in this example is an event counter; it is initialized to 0 and incremented only when a certain event occurs. The counter in the previous example was an iteration counter; it was initialized to 1 and incremented during each iteration of the loop.
3e26ecb1b6ac508ae10a0e39d2fb98b2.gif 3e26ecb1b6ac508ae10a0e39d2fb98b2.gif
Event Counter A variable that is incremented each time a particular event occurs.
Keeping Track of a Previous Value
Sometimes we want to remember the previous value of a variable. Suppose we want to write a program that counts the number of not-equal operators (!=) in a file that contains a C++ program. We can do so by simply counting the number of times an exclamation mark (!) followed by an equal sign (=) appears in the input. One way in which to do this is to read the input file one character at a time, keeping track of the two most recent characters, the current value and the previous value. In each iteration of the loop, a new current value is read and the old current value becomes the previous value. When EOF is reached, the loop is finished. Here's a program that counts not-equal operators this way:
//******************************************************************
// NotEqualCount program
// This program counts the occurrences of != in a data file
//******************************************************************
#include <iostream.h>
#include <fstream.h>   // For file I/O

int main()
{
    int      count;        // Number of != operators
    char    prevChar;      // Last character read
    char     currChar;     // Character read in this loop iteration
    ifstream inFile;       // Data file

    inFile.open(myfile.dat);          // Attempt to open input file
    if ( !inFile )                    // Was it opened?
    {
        cout << ** Can't open input file ** // No--print message
             < endl;
        return 1;                            // Terminate program
    }
    count = 0;                  // Initialize counter
    inFile.get(prevChar);       // Initialize previous value
    inFile.get(currChar);       // Initialize current value
    while (inFile)              // While previous input succeeded...
    {

 
< previous page page_268 next page >