cgetcharkernighan-and-ritchieputchar

Putchar and Getchar in C


I'm reading K&R's The C Programming Language and have become confused on putchar and getchar. I made a program where you enter 10 chars and the program prints them back out to the screen.

#include <stdio.h>

int main() 
{
    int i;
    int ch;
    for(i = 0; i < 10; i++)
    {
        printf("Enter a single character >> ");
        ch = getchar();
        putchar(ch);
    }

    return 0;
}

I expected to get an output like this:

Enter a single character >> a
a
Enter a single character >> b
b

...and so on 10 times but this is the output I got: (I stopped after entering 2 chars)

Enter a single character >> a
aEnter a single character >>
Enter a single character >> b
bEnter a single character >>
Enter a single character >>

not sure why my input character is being combined with the fixed string and being output.

Also, I'm not too sure why ints are used to store characters.


Solution

  • putchar(ch);
    

    just prints single character and the following printf continues within the same line. Simply add:

    putchar('\n');
    

    right after putchar(ch);, which will explicitly start the new line before the printf is executed. Additionally you should also take '\n' from the input which stays there after you enter the character:

    for(i = 0; i < 10; i++)
    {
        printf("Enter a single character >> ");
        ch = getchar();
        getchar();        // <-- "eat" new-line character
        putchar(ch);
        putchar('\n');    // <-- start new line
    }