1

I have this following line of code: while((temp = getchar())!= EOF){printf("Hello");}

I expected the program to print Hello for every char read, but it prints for every enter pressed instead. How can I change it to my intention?

Gerhardh
  • 11,688
  • 4
  • 17
  • 39
  • It's obvious because enter is also a character defined in ASCII code – Bip Lob Dec 06 '21 at 08:34
  • 1
    It's related to buffering. See https://stackoverflow.com/questions/1798511/how-to-avoid-pressing-enter-with-getchar-for-reading-a-single-character-only – Avi Dec 06 '21 at 08:36
  • 1
    Does this answer your question? [How to avoid pressing Enter with getchar() for reading a single character only?](https://stackoverflow.com/questions/1798511/how-to-avoid-pressing-enter-with-getchar-for-reading-a-single-character-only) – Ken Y-N Dec 06 '21 at 08:37
  • When you press enter, `getchar` starts reading from start of the line to the end. – Barmak Shemirani Dec 06 '21 at 14:10

1 Answers1

0

when you enter a character from the keyboard, every character goes into a buffer, including the enter(\n) character. getchar function will take each character in the buffer in turn and of course will include the enter character. You have to check the return character of getchar function is enter or not:

while ((temp = getchar()) != EOF) {
    if (temp != '\n') {
        printf("Hello\n");
    }          
}
duong.ld
  • 76
  • 5
  • 1
    it still prints only when enter is pressed. – אורי ארצי וייס Dec 06 '21 at 09:12
  • 1
    You want to print as soon as you type a character? If using getchar function, very difficult. Because getchar gets the character from the buffer and to get the character into the buffer you have to press enter. Use kbhit() to check when you type a character and getch() to get character instead might solve your problem – duong.ld Dec 06 '21 at 09:16