-2

In the program, printf("%d", getchar()) is printing an extra 10.

when i give input like a, it prints 9710 instead of 97, same for others

#include <stdio.h>

int main() {

    int c;
    while((c=getchar()) != EOF) {
        printf("%d", c);
    }
    printf("\n\tENDED\n\n");

    return 0;
}
me@Device-xx:~/Desktop/Test/Tmps$ gcc 118.c -o 118
me@Device-xx:~/Desktop/Test/Tmps$ ./118
a
9710s
11510x
12010
Mathieu
  • 8,840
  • 7
  • 32
  • 45

1 Answers1

4

You didn't pass a to STDIN. Because you pressed a and Enter, you passed a and a Line Feed. Assuming an ASCII-based encoding (such as UTF-8),

  1. The letter a is encoded as 0x61 = 97
  2. A Line Feed is encoded as 0x0A = 10

Maybe you want

while (1) {
    int c = getchar();
    // Stop when a Line Feed or EOF is encountered.
    if (c == EOF || c == 0x0A) {
         break;
    }

    printf("%d", c);
}
ikegami
  • 367,544
  • 15
  • 269
  • 518