LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 674|回复: 3

变量类型转换问题

[复制链接]
发表于 2010-6-30 18:33:19 | 显示全部楼层 |阅读模式
代码如下:


  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类型了,怎么后来还可以把字符串赋值给它?
发表于 2010-7-1 10:17:20 | 显示全部楼层
首先,这个跟你标题里的static无关吧
其次,哪里有把字符串赋值给它?
回复 支持 反对

使用道具 举报

 楼主| 发表于 2010-7-1 10:40:11 | 显示全部楼层
peek_character是int,ch是char,代码有一段是“peek_character = ch”,这是隐式类型转换吗?
回复 支持 反对

使用道具 举报

发表于 2010-7-1 12:40:08 | 显示全部楼层
Post by sherman;2100721
peek_character是int,ch是char,代码有一段是“peek_character = ch”,这是隐式类型转换吗?
这样当然没有问题
话说在C中,字符常量本来就是当成int存放的,不信sizeof('a')看是结果是多少.另外类似getchar这样的函数,你去查原型到底是"int getchar(void)"还是"char getchar(void)"
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表