1 Replies - 1408 Views - Last Post: 04 July 2011 - 04:43 AM Rate Topic: -----

#1 no2pencil  Icon User is online

  • Professor Snuggly Pants
  • member icon

Reputation: 6595
  • View blog
  • Posts: 30,788
  • Joined: 10-May 07

read unbuffered input

Posted 02 October 2010 - 07:36 PM

Description: The preprocessor arguments allow for this code to compile on both Linux & Windows operating systems. The only draw back is that the non-portable conio.h header from Borland is required for this code to work on Windows.This code will allow you to create a menu that responds to keypress. You don't have to have your users hit enter, or scan for return from the keyboard buffer.
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <time.h>
#if defined(linux)||defined(CYGWIN32)
  #define OSLi
  #include <termios.h>
  #include <sys/time.h>
#elif defined(WINDOWS)||defined(WIN32)
  #define OSWIN
  #include <conio.h>
#endif

int menu(void);

int main(void) {
  int i=0;
  #ifdef OSLi
    system("clear");
  #else
    system("cls");
  #endif
  while(i==0) i=menu();
  
  return 0;
}

int menu(void) {
  char buff[32]; // 32 bit buffer
  char ch='�';
  int i=0;

  #ifdef OSLi
          struct termios oldSettings, newSettings;
  #endif

  printf("Pick one...n");
  printf("[A] Example An");
  printf("[B] Example Bn");
  printf("[C] Example Cn");
  printf("[Q] Quitnn");

  #ifdef OSLi
    tcgetattr( fileno( stdin ), &oldSettings );
    newSettings = oldSettings;
    newSettings.c_lflag &= (~ICANON & ~ECHO);
    tcsetattr( fileno( stdin ), TCSANOW, &newSettings );
  #endif

  // Parse for empty char
  while(ch=='�') {
    #ifdef OSLi
        ch=toupper(getchar());
    #else
        ch=toupper(getch());
    #endif
  }
  printf("Your choice: ");
  switch(ch) {
    case 'A':
    sprintf(buff,"Option A!");
    break;

    case 'B':
    sprintf(buff,"Option B!");
    break;

    case 'C':
    sprintf(buff,"Option C!");
    break;
    
    case 'Q':
    sprintf(buff,"Quit!");
    #ifdef OSLi  // Restore stdin
      tcsetattr( fileno( stdin ), TCSANOW, &oldSettings );
    #endif
    i++;
    break;
    default: // We shouldn't get this far,
             // with proper error checking!
    printf("You didn't type it right!n");
    break;
  }
  printf("%sn",buff);
  printf("Thank you for reading our tutorial!n");
  return i;
}



Is This A Good Question/Topic? 0
  • +

Replies To: read unbuffered input

#2 hulla  Icon User is offline

  • Writing Lines


Reputation: 49
  • View blog
  • Posts: 733
  • Joined: 05-March 11

Re: read unbuffered input

Posted 04 July 2011 - 04:43 AM

Cool
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1