一个无聊的自动提款机程序---改进版--忽略非法输入

/*
 * 自动提款机程序,他会问用户很多的yes/no的问题
 * 
 * atm.sh
 * 
 * while true
 * do 
 * 	do_a_transaction # run a program
 *      if play_again    # run our program
 *	then   		 
 * 	    continue     # if "y" loop back
 * 	fi
 *	break            # if "n" break
 * done
 *
 * 这个银行脚本程序将程序的各个组件组合起来
 * 1.第一个称为do_a_transaction的程序,完成ATM的工作
 * 2.第二个组件play_again,从用户得到回答
 * 
 *
 */

 /*
  * PLAY_AGAIN.C
  * 功能:实现组件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的mode
	tty_mode(0);

	//设置tty的mode
	set_crmode();

	//获得回答
	response = get_response(QUESTION);
	
	//恢复tty的mode
	tty_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");

		    /*
		     * 当输入sure,没有显示任何内容,他会忽略错误信息
 	 	     *
		     *
		     */
		}
	
	}
  
  }

set_crmode(){
	
	struct termios ttystate;

	//读取当前的终端驱动属性
	tcgetattr(0,&ttystate);
	
	//修改配置

	//关闭缓冲
	ttystate.c_lflag &= ~ICANON;

        //关闭回显
	ttystate.c_lflag &= ~ECHO;

	//保证一次仅获得一个字符
	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);
	}else
		return tcsetattr(0,TCSANOW,&original_mode);

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值