曲径通幽论坛

标题: getchar [打印本页]

作者: beyes    时间: 2008-11-16 23:12
标题: getchar
NAME
[blockquote]getchar - get a byte from a stdin stream[/blockquote]SYNOPSIS
[blockquote]#include <stdio.h>

int getchar(void);

[/blockquote]DESCRIPTION
[blockquote]The getchar() function shall be equivalent to getc(stdin).
[/blockquote]RETURN VALUE
[blockquote]Refer to fgetc().
[/blockquote]ERRORS
[blockquote]Refer to fgetc().
[/blockquote]
The following sections are informative.EXAMPLES
[blockquote]None.
[/blockquote]APPLICATION USAGE
[blockquote]If the integer value returned by getchar() is stored into a variable of type charand then compared against the integer constant EOF, the comparison maynever succeed, because sign-extension of a variable of type char on widening to integer is implementation-defined.
[/blockquote]RATIONALE
[blockquote]None.
[/blockquote]FUTURE DIRECTIONS
[blockquote]None.
[/blockquote]SEE ALSO
getc(), the Base Definitions volume of IEEE Std 1003.1-2001, <stdio.h>
作者: beyes    时间: 2008-11-16 23:12
函数名: getchar
  功 能: 从stdin流中读字符
  用 法: int getchar(void);
  注解:
  getchar有一个int型的返回值.当程序调用getchar时.程序就等着用户按键.用户输入的字符被存放在键盘缓冲区中.直到用户按回车为止(回车字符也放在缓冲区中).当用户键入回车之后,getchar才开始从stdin流中每次读入一个字符.getchar函数的返回值是用户输入的第一个字符的ASCII码,如出错返回-1,且将用户输入的字符回显到屏幕.如用户在按回车之前输入了不止一个字符,其他字符会保留在键盘缓存区中,等待后续getchar调用读取.也就是说,后续的getchar调用不会等待用户按键,而直接读取缓冲区中的字符,直到缓冲区中的字符读完为后,才等待用户按键.
  getch与getchar基本功能相同,差别是getch直接从键盘获取键值,不等待用户按回车,只要用户按一个键,getch就立刻返回,getch返回值是用户输入的ASCII码,出错返回-1.输入的字符不会回显在屏幕上.getch函数常用于程序调试中,在调试时,在关键位置显示有关的结果以待查看,然后用getch函数暂停程序运行,当按任意键后程序继续运行.
  程序例:
  #include <stdio.h>
  int main(void)
  {
  int c;
  /* Note that getchar reads from stdin and
  is line buffered; this means it will
  not return until you press ENTER. */
  while ((c = getchar()) != '\\n')
  printf("%c", c);
  return 0;
  }
  注:可以利用getchar()函数让程序调试运行结束后等待编程者按下键盘才返回编辑界面,用法:在主函数结尾,return 0;之前加上getchar();即可

又如程序段:
    c = getchar();
    printf("%c ", c );

    c = getchar();
    printf("%c ", c );

    c = getchar();
    printf("%c ", c );

    c = getchar();
    printf("%c ", c );

    c = getchar();
    printf("%c ", c );
---------------------------
此时输入 hellok
那么将输出h e l l o




欢迎光临 曲径通幽论坛 (http://www.groad.net/bbs/) Powered by Discuz! X3.2