+ -
当前位置:首页 → 问答吧 → 请教static变量问题

请教static变量问题

时间:2010-06-30

来源:互联网

  1. #include <stdio.h>
  2. #include <termios.h>
  3. #include <term.h>
  4. #include <curses.h>
  5. #include <unistd.h>

  6. static struct termios initial_settings, new_settings;
  7. static int peek_character = -1;

  8. void init_keyboard();
  9. void close_keyboard();
  10. int kbhit();
  11. int readch();

  12. int main()
  13. {
  14. int ch = 0;

  15. init_keyboard();
  16. while(ch != 'q') {
  17. printf("looping\n");
  18. sleep(1);
  19. if(kbhit()) {
  20. ch = readch();
  21. printf("you hit %c\n",ch);
  22. }
  23. }
  24. close_keyboard();
  25. exit(0);
  26. }

  27. void init_keyboard()
  28. {
  29. tcgetattr(0,&initial_settings);
  30. new_settings = initial_settings;
  31. new_settings.c_lflag &= ~ICANON;
  32. new_settings.c_lflag &= ~ECHO;
  33. new_settings.c_lflag &= ~ISIG;
  34. new_settings.c_cc[VMIN] = 1;
  35. new_settings.c_cc[VTIME] = 0;
  36. tcsetattr(0, TCSANOW, &new_settings);
  37. }

  38. void close_keyboard()
  39. {
  40. tcsetattr(0, TCSANOW, &initial_settings);
  41. }

  42. int kbhit()
  43. {
  44. char ch;
  45. int nread;

  46. if(peek_character != -1)
  47. return 1;
  48. new_settings.c_cc[VMIN]=0;
  49. tcsetattr(0, TCSANOW, &new_settings);
  50. nread = read(0,&ch,1);
  51. new_settings.c_cc[VMIN]=1;
  52. tcsetattr(0, TCSANOW, &new_settings);

  53. if(nread == 1) {
  54. peek_character = ch;
  55. return 1;
  56. }
  57. return 0;
  58. }

  59. int readch()
  60. {
  61. char ch;

  62. if(peek_character != -1) {
  63. ch = peek_character;
  64. peek_character = -1;
  65. return ch;
  66. }
  67. read(0,&ch,1);
  68. return ch;
  69. }
复制代码
不明白为何peek_character在开始已经声明是int类型了,怎么后来还可以把字符串赋值给它?

作者: sherman-zhang   发布时间: 2010-06-30

字符串在哪?

作者: wmmy2008   发布时间: 2010-06-30

你关心的是 static 还是 把char型赋值给int型?

作者: donglongchao   发布时间: 2010-06-30

回复 donglongchao


    两个都关心,可以帮忙讲解一下吗?谢谢!

作者: sherman-zhang   发布时间: 2010-06-30

回复 wmmy2008


    应该是字符型变量ch。ch 被定义为char。

作者: sherman-zhang   发布时间: 2010-06-30