If we can read the input stock data from a file, we can make use of a property every file has - it has an end. The built-in function scanf() can detect the end of the file.
Recall, when the statement:
scanf("%d", &shares);
is executed, one integer is read from stdin, converted to internal representation, and stored in the cell, shares.
But what if there is no more data in the file?
i.e. we have reached the end of the file?
In that case, scanf() DOES NOTHING to the cell shares (it has no data value to put in there). Instead it returns a status value AS THE VALUE OF THE FUNCTION indicating it was not able to complete the request.
We can capture this return value in a variable and test to see if scanf() has detected the end of the file. The symbolic name of the value returned by scanf() when it detects end of file is EOF.
The algorithm remains:
Initialize the portfolio cost and portfolio value
Get the number of shares for the first stock
while there are more stocks to proccess
Get the selling price for the stock
Get the purchase price for the stock
Print the data values for the stock
Accumulate the portfolio cost for the stock
Accumulate the portfolio value for the stock
Get the number of shares for the next stock
Compute the profit
Print the result
The implementation of this algorithm is in stock4.eof.c
The include directive.
#include <stdio.h>
This tells the compiler to "include" a system file called stdio.h. This file contains (among other things) the definition of EOF.
We assign the return status value from scanf() to the integer variable, flag.
flag = scanf("%d", &shares);
We test flag for EOF in the while condition
while( flag != EOF )
We update flag at the bottom of the loop:
flag = scanf("%d", &shares);
We can run this program with data coming from a file using redirection.
i.e. with input comping from the keyboard?
We simply need to indicate a "fake" end of file from the keyboard.
In Unix, we do this with the ^D (control-D) keystroke. (In dos EOF is ^Z).
We can even do away with the flag variable, and test the return value of scanf() in the while condition directly as in stock4.eof2.c