so I've been teaching myself C and I've come across the 'getchar()' and 'putchar()' methods from 'stdio.h'. As I understand it, 'getchar()' takes the most recent character from the text stream and stores it into a variable whilst 'putchar()' takes this variable and prints it to the terminal.
So I've written the following piece of code:
#import<stdio.h>
void main () {
printf("Enter a character and it will be repeated back to you:\n");
int c;
while (c != EOF) {
c = getchar();
printf("You entered : ");
putchar(c);
printf("\n");
}
}
and I expected it to read the keyboard input and print it to the screen one character at a time. As an example, if I were to type "home", the output would be:
You entered : h You entered : o You entered : m You entered : e
but instead i get:
home You entered : h You entered : o You entered : m You entered : e
The characters are printed as im typing and then repeated afterwards. I'm not quite sure what I'm doing wrong here or if I am doing anything wrong and just don't quite grasp the concept. Can anyone explain whats happening here?
cis uninitialized the first time it's used. You will also passEOFtoputcharwhen you read it, which you shouldn't do. - Tom Karzesvoid main()should beint main(void). If you have a book that tells you to usevoid main(), its author doesn't know C well enough to be writing about it. (Unless it's referring to some specific freestanding implementation, but that's unlikely.) - Keith Thompson#include <stdio.h>. Leaveimportto python... - David C. Rankinint, however, in modern C, that is a problem and you have to explicitly state:intas the returned type - user3629249