JohnBigs
JohnBigs

Reputation: 2811

Cant get the correct value of ASCII using getchar()

It's probably a simple correction since the program is super short but please help me understand why am i getting weird output:

#include <stdio.h>

int main(void)

{
    char x;
    printf("please enter a word, and ctrl + d to see the resault\n");

    while ((x = getchar()) != EOF)
    {
        printf("%d", x);
    }


    return 0;
}

intput: 'd'
output: 10010

Upvotes: 0

Views: 2109

Answers (3)

unwind
unwind

Reputation: 399803

This is because you're truncating the return value.

getchar() returns int, look at any documentation.

It has to be this way, since EOF can't be allowed to "collide" with any character. Since int is larger than char, this allows EOF to be somewhere inside the space of numbers expressible as int, while being outside the set of char.

As explained by user876651, the output "10010" is in fact two decimal integers that are printed next to each other:

  • 100 is the ASCII code for the lower-case letter 'd'
  • 10 is ASCII for the linefeed '\n'

You should print with a newline: printf("%d\n", x); to get these on lines of their own.

Upvotes: 2

Crog
Crog

Reputation: 1170

The reason you get 10010 is because you are pressing 'd' followed by 'return'.

Change your printf format to "%d\n" to visualize this more easily.

A fix could be:

while ((x = getchar()) != '\n' )
{
}

Upvotes: 3

Rohan
Rohan

Reputation: 53326

Change char x to int x as getchar() returns int and that is what you are trying to print.

edit:

getchar() to work, you need to press enter i.e. \n which will also get printed.

Upvotes: 1

Related Questions