not using enter

Apr 24, 2008 at 10:19am
I wanted to use this program without having to press enter. scanf and getchar both require U 2. Any suggestions?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <stdio.h>
#include <time.h>
#include <stdlib.h>

int main()
{
	char kill;
	srand((unsigned)time(NULL));
	puts("HIDDEN KILL!");
	printf("press a lowercase letter and enter. try to stay alive!\n");
	kill = rand() % 25 + 97;
	while(getchar() != kill);
	return(0);
}
Apr 24, 2008 at 11:09am
By default, stdin is line-buffered, which means your application doesn't see the data until the user presses ENTER. What you want is an unbuffered stdin so that getchar() receives the keypress immediately.

Fortunately, it's not too hard. Warning, though, I tested this code on Linux, but I don't know if it works on "other" operating systems.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <stdio.h>
#include <fcntl.h>
#include <termios.h>
#include <iostream>

int main()
{
    struct termios oldSettings, newSettings;

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

    while ( 1 )
    {
        char ch = getchar();
        std::cout << "Read character: " << ch << std::endl;
    }

    // This is how to restore stdin, if you need/want to:
    tcsetattr( fileno( stdin ), TCSANOW, &oldSettings );
    return 0;
}

Apr 24, 2008 at 11:38am
BTW, it is the turning off of canonical mode (~ICANON) that does the trick. My sample code also turns off character echoing (~ECHO) so that the keystroke is not echoed to the screen when you type it. Makes it easier to see that the code does what you need.
Apr 24, 2008 at 2:56pm
On Windows, you can take advantage of the conio library.

The code jsmith gave was for Linux, BSD and others, where termios is available.

This is an platform-specific question because different platforms do things with hardware differently. For example, Windows reads and writes things differently from Linux. In addition, Windows barely allows Assembly code to interface with hardware these days (something that continues to anger me when I want to learn about the low-level things like I could with MS-DOS :P).
Last edited on Apr 24, 2008 at 2:57pm
Apr 25, 2008 at 10:12am
I am using Windows vista with Microsoft Visual C++ 2008 Express Edition. I don't have the termios
Last edited on Apr 25, 2008 at 10:16am
Topic archived. No new replies allowed.