There are multiple issues in the code fragment:
-
The
ch = scanf("%c", &ch);
serves no purpose and does not even properly read a byte from the file intoch
. Note thatscanf
does store the byte intoch
, but it is immediately overwritten as you store the return value intoch
as well. Just remove this line. -
while ((ch = getchar()) != EOF) { printf("%c\n", ch); }
is correct for your purpose but the type ofch
must beint
instead ofchar
to accommodate all values ofunsigned char
and the special valueEOF
. As currenly written, your code will fail to stop at end of file on platforms wherechar
is an unsigned type.
3
solved Why doesn’t the first letter of my string print?