ccharnewlinegetcharputchar

Unexpected input when using getchar(), and unexpected output using putchar()


I am new to c and understand very little of it however as far as i understand it this code should either print the character i enter (it should print it twice), or print the number representation of the bits for my character then my character (before asking for input again for 100 loops) however it seems to do neither.

instead it prints some random numbers (i assume the representation as a number) then the letter, then 10.

i am using gcc to compile it in on ubuntu 18.04 running on wsl if that makes any difference at all. once again im a total newb so i don't know if that is even a possible point of error.

Here is my code:

#include <stdio.h>
int c;


 int main() {
    
 
    for(int x =0; x < 100; x++){
        c = getchar();
        printf("%d", c);
        putchar( c );

    }
}

example:

input: f

output: 102f10

or

input: r

output: 114r10


Solution

  • After you entered a character that is read by this call

    c = getchar();
    

    then the input buffer stored also the new line character '\n' that appeared due to pressing the Enter key.

    Thus in this loop

    for(int x =0; x < 100; x++){
        c = getchar();
        printf("%d", c);
        putchar( c );
    
    }
    

    if you entered for example the character 'f' then this call

        printf("%d", c);
    

    outputted its internal code

    102
    

    after that the next call

        putchar( c );
    

    outputted the character itself.

    f
    

    Now the input buffer contains the new line character '\n'. And in the next iteration of the loop its internal representation

    10
    

    is outputted by the call

        printf("%d", c);
    

    Instead of the call

    c = getchar();
    

    use

    scanf( " %c", &c );
            ^
    

    pay attention to the blank in the format string. In this case white space characters as for example the new line character '\n' will be skipped.