getchar() is giving output in C

巧了我就是萌 提交于 2019-12-12 01:53:01

问题


What should this program do,

#include<stdio.h>
main()
{   
  getchar();
}

I expect it to show a blank screen until I hit any character on the keyboard. But what it does is quite weird. It displays whatever I press. It never terminates until I press Enter.

As far as I know, getchar() should just read one character. It should not output anything.

  • Why is it printing every character that I input?

Edit:

Why doesn't getchar() stop after reading one character, e.g. in this code:

   #include <stdio.h>  

   main()  

   {  

    getchar();  

   printf("Done");  


  }  

The program should print Done after reading one character.


回答1:


Your program won't terminate until getchar() completes. getchar() does not complete until the input buffer is populated. The input buffer is not populated until you press 'Enter'.

The character you are seeing is the character you are typing. This is default terminal-driven behavior, not driven by your program.




回答2:


You are pressing key, so your console is showing same character to you. It's expected behaviour. getch() will also return ascii value of character that is being printed on screen.




回答3:


What getchar basically does is reading from stdin. This is a file with file descriptor 0 and it usually refers to the terminal that you type in (unless you change it to some file via <, e.g. cat < sample.txt). Like with any file, you can call read on file 0 - in case of the terminal, read will respond as soon as you type something into the terminal and hit enter. Unless you do so, the call to read on stdin just waits until it gets something to read. This is why your program is waiting: It calls read on stdin (file 0), and since stdin is the terminal, read will only return when you hit enter. I hope you have some understanding on file handling, otherwise this answer might confuse you a bit.



来源:https://stackoverflow.com/questions/27297811/getchar-is-giving-output-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!