一个无聊的自动提款机程序---改进版--修改终端属性
来源:互联网 发布:程序员思维导图 编辑:程序博客网 时间:2024/05/01 00:41
/* * 功能:实现组件2 * * 对用户显示提示问题 * 接受输入 * 如果是y,返回0 * 如果是n,返回1 * */ #include <stdio.h> #include <termios.h> #define QUESTION "Do you want another transaction" int get_response(char *); int set_crmode(); int tty_mode(int); /* * 这个版本的play_again改进的问题包括 * 关闭规范输入,使得程序能够在用户敲击键盘的同时得到输入的字符 * * */ int main(){ int response;//保存tty的modetty_mode(0);//设置tty的modeset_crmode();//获得回答response = get_response(QUESTION);//恢复tty的modetty_mode(1);return response; } int get_response(char *question){ printf("%s(y/n)?",question);int input;while(1){//循环读取用户的输入,指导用户输入ynYN//switch(input=getchar()){ case 'y': case 'Y':return 0; case 'n': case 'N': case EOF:return 1; default: printf("\ncan not understand %c,",input); printf("Please type y or n \n");}} }set_crmode(){struct termios ttystate;//读取当前的终端驱动属性tcgetattr(0,&ttystate);//修改配置//关闭规范模式--关闭缓冲ttystate.c_lflag &= ~ICANON;//保证一次仅获得一个字符ttystate.c_cc[VMIN] == 1;//保存修改tcsetattr(0,TCSANOW,&ttystate);}tty_mode(int how){static struct termios original_mode;if(how == 0){tcgetattr(0,&original_mode);}elsereturn tcsetattr(0,TCSANOW,&original_mode);}