简体   繁体   English

getchar()在C中给出输出

[英]getchar() is giving output in C

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. 直到我按Enter键,它才会终止。

As far as I know, getchar() should just read one character. 据我所知,getchar()应该只读取一个字符。 It should not output anything. 它不应输出任何内容。

  • Why is it printing every character that I input? 为什么要打印我输入的每个字符?

Edit: 编辑:

Why doesn't getchar() stop after reading one character, eg in this code: 为什么getchar()在读取一个字符后没有停止,例如在以下代码中:

   #include <stdio.h>  

   main()  

   {  

    getchar();  

   printf("Done");  


  }  

The program should print Done after reading one character. 读取一个字符后,程序应打印完成。

Your program won't terminate until getchar() completes. 直到getchar()完成,您的程序才会终止。 getchar() does not complete until the input buffer is populated. 在填充输入缓冲区之前, getchar()不会完成。 The input buffer is not populated until you press 'Enter'. 直到按“ Enter”键,才会填充输入缓冲区。

The character you are seeing is the character you are typing. 您看到的字符就是您键入的字符。 This is default terminal-driven behavior, not driven by your program. 这是默认的终端驱动行为,而不是由程序驱动。

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. getch()还将返回在屏幕上打印的字符的ascii值。

What getchar basically does is reading from stdin. getchar基本上所做的是从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 < , eg cat < sample.txt ). 这是一个文件描述符为0的文件,通常指您键入的终端(除非您通过<将其更改为某个文件,例如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 . 与任何文件一样,您可以在文件0上调用read在终端机的情况下,只要在终端机中输入内容并按enter键read就会响应。 Unless you do so, the call to read on stdin just waits until it gets something to read. 除非您这样做,否则在stdin上进行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. 这就是程序等待的原因:它在stdin(文件0)上调用read ,并且由于stdin是终端,因此只有在按Enter键时read才会返回。 I hope you have some understanding on file handling, otherwise this answer might confuse you a bit. 希望您对文件处理有所了解,否则此答案可能会使您感到困惑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM