1
0

play_again1.c 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /* play_again1.c
  2. * purpose: ask if user wants another transaction
  3. * method: set tty into char-by-char mode, read char, return result
  4. * returns: 0=>yes, 1=>no
  5. * better: do no echo inappropriate input
  6. */
  7. #include <stdio.h>
  8. #include <termios.h>
  9. #define QUESTION "Do you want another transaction"
  10. main()
  11. {
  12. int response;
  13. tty_mode(0); /* save tty mode */
  14. set_crmode(); /* set chr-by-chr mode */
  15. response = get_response(QUESTION); /* get some answer */
  16. tty_mode(1); /* restore tty mode */
  17. return response;
  18. }
  19. int get_response(char *question)
  20. /*
  21. * purpose: ask a question and wait for a y/n answer
  22. * method: use getchar and complain about non y/n answers
  23. * returns: 0=>yes, 1=>no
  24. */
  25. {
  26. int input;
  27. printf("%s (y/n)?", question);
  28. while(1){
  29. switch( input = getchar() ){
  30. case 'y':
  31. case 'Y': return 0;
  32. case 'n':
  33. case 'N':
  34. case EOF: return 1;
  35. default:
  36. printf("\ncannot understand %c, ", input);
  37. printf("Please type y or no\n");
  38. }
  39. }
  40. }
  41. set_crmode()
  42. /*
  43. * purpose: put file descriptor 0 (i.e. stdin) into chr-by-chr mode
  44. * method: use bits in termios
  45. */
  46. {
  47. struct termios ttystate;
  48. tcgetattr( 0, &ttystate); /* read curr. setting */
  49. ttystate.c_lflag &= ~ICANON; /* no buffering */
  50. ttystate.c_cc[VMIN] = 1; /* get 1 char at a time */
  51. tcsetattr( 0 , TCSANOW, &ttystate); /* install settings */
  52. }
  53. /* how == 0 => save current mode, how == 1 => restore mode */
  54. tty_mode(int how)
  55. {
  56. static struct termios original_mode;
  57. if ( how == 0 )
  58. tcgetattr(0, &original_mode);
  59. else
  60. return tcsetattr(0, TCSANOW, &original_mode);
  61. }