There is a bug common to all 5 versions: we should always test whether the read was successful.
- For
scanf()
: did it return1
, when we asked for one conversion?For
scanf()
: did it return1
, when we asked for one conversion? - For
getchar()
: did it returnEOF
?For
getchar()
: did it returnEOF
?Note, in particular, that narrowing the result of
getchar()
(which isint
) to anunsigned char
loses the ability to distinguishEOF
from a valid character.
Note, in particular, that narrowing the result of getchar()
(which is int
) to an unsigned char
loses the ability to distinguish EOF
from a valid character.
Here's a corrected version:
#include <stdio.h>
int main(void)
{
int d;
while ((d = getchar()) != EOF) {
if (d != '\n')
printf("%d\n", d * d);
}
}
Finally, a pedantic note: this will only work on ASCII values when run on an ASCII system/locale. In other words, C always uses the environment's character coding, and does not convert input to a fixed representation as done by, say, Java.