The guy is using input stream redirection in order to use
getchar
to perform
fgetc[
^] task, that is reading a character at time from a file.
In the
ReadInt
function, blanks and newlines are skipped, then digits are then read and used to build the resulting integer, until a blank, a newline or the end of file is found.
The key statements for building the integer from read digits are:
int out=0;
while()
{
out *= 10;
out+=(c-'0');
That is
out
is initalised with zero, then at each step it is first multiplied by 10 and then added with the read digit value (e.g.
'5' - '0' == 5
).
Suppose you are reading the 55 number from the file.
out=0
before reading any digitout
is still 0 after performing the multiplication by 10
out=5
, after performing out+=c - '0'
, the first timeout=50
, after perorming out*=10
at next stepout=55
, after performing out+=c - '0'
again- finally a blank is detected and the function return
55
Please note, the function is not robust: it relies on the fact that every character different from a blank a newline (or the end of file) is a digit (that is not true, generally speaking, so this must be a prerequisite on your input files.
There is no overflow checking on integers (as well negative values are not correctly parsed).
Moreover it may return a spurious zero at the end of the file.