In the following code example from K&R's book, if I replace putchar(c)
with printf("%c", c)
the code works the same. But if I replace it with printf("%d", c)
it gives gibberish output.
#include <stdio.h>
int main() {
int c;
c = getchar();
while (c != EOF) {
putchar(c);
c = getchar();
}
}
From here, I learned that the getchar()
converts the stdin to an 8-bit character whose value ranges from 0 to 255.
Now I want to print the value of c
using putchar(c)
in one line and printf("%d", c)
in another line. So I wrote the following code:
#include <stdio.h>
int main() {
int c, b;
c = getchar();
b = c;
while (c != EOF && c != 10) {
printf("%c",c);
c = getchar();
}
printf("\n");
while (b != EOF && b != 10) {
printf("%d\t",b);
b = getchar();
}
}
I used the condition c != 10
as the newline character is read as 10
by getchar()
. I expected the code to work as
$ ./a.out
783
783
55 56 51
but the program terminates as
$ ./a.out
783
783
55
I understand that getchar()
takes input from stdin and the variable b
is not stdin. So how should I copy the variable c
to b
so that my program works as I expect it to?