Results 1 to 5 of 5

Thread: basic keyboard input in linux?

  1. #1
    Junior Member
    Join Date
    Feb 2009
    Posts
    34

    Default basic keyboard input in linux?

    Does any one know of a way to read input from the keyboard without having to press enter? This is what I have so far, but it requires pressing enter after every key...

    Code:
        char key;
        char buf[1];
    
        while(1) 
        {        
            read(0, buf, 1);
            key = buf[0];     
    
            switch (key)
            {
                case 0x77:  // ASCII w
                    printf("w pressed\n");
                    break;
                .
                .
                .
    
                case 0x1b:  // ASCII  esc
                    printf("esc pressed \n");
                    return(0);
                    break;
                default:
                    printf("this should not print\n");
            } 
            fflush(stdin);
       }
    "You shot who in the what now?"

  2. #2
    Junior Member
    Join Date
    Jan 2010
    Posts
    79

    Default

    Have you looked at getc or getchar?

  3. #3
    Member imported_blackfoot's Avatar
    Join Date
    Jun 2007
    Posts
    386

    Default language

    As stated use getc but test it so that 'it' will know when you have finished and 'it' will test for errors or overflows.

    Polite suggestion: whenever you make enquiries please declare the name of the language you are using to give benefit to a wider number of readers.
    Lux sit

  4. #4
    Junior Member
    Join Date
    Feb 2009
    Posts
    34

    Default

    Thanks for the suggestions, but getc and getchar don't seem to work either. Both wait for 'enter' key to be pressed before sending the character the user typed to stdio. I just changed the two lines in the above C code from this...

    Code:
    read(0, buf, 1);
    key = buf[0];
    to this...

    Code:
    key = getc(stdin);
    after some more digging found out that putting the terminal into "raw" mode is one way to solve this problem

    Code:
    char key;
    system("stty raw");     /* put terminal into raw mode */
    key = getc(stdin);
    .
    .
    .
    system("stty cooked");  /* put terminal back into normal mode */
    "You shot who in the what now?"

  5. #5
    Member imported_blackfoot's Avatar
    Join Date
    Jun 2007
    Posts
    386

    Default cbreak

    cbreak is another option if you are not protecting within a loop
    Lux sit

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •