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

#1 no2pencil   User is online

  • Professor Snuggly Pants
  • member icon

Reputation: 6889
  • View blog
  • Posts: 31,709
  • 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>

int menu(void);

int main(void) {
  int i=0;
  #ifdef OSLi
  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;

  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 );

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

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

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

Is This A Good Question/Topic? 0
  • +

Replies To: read unbuffered input

#2 hulla   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

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1