Newbie
Newbie

Reputation: 31

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

Upvotes: 1

Views: 269

Answers (3)

Steve Summit
Steve Summit

Reputation: 48033

When your program's output is confusing, with stuff jammed together, it helps to break things up instead. Try this program instead:

int main() {
    for(int x =0; x < 100; x++){
        c = getchar();
        printf("got character %c = %d\n", c, c);
    }
}

Upvotes: 1

Vlad from Moscow
Vlad from Moscow

Reputation: 311088

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.

Upvotes: 2

Nastor
Nastor

Reputation: 638

That is because you're printing the ASCII representation as integer of the character you're inputting by doing printf("%d",c). If you want the character you inputted to be printed on the console as a character only, you should just remove printf and use putchar.

Upvotes: 1

Related Questions