tags:

views:

1398

answers:

3

Hey guys. So I am using getch() and my app crashes instantly. Including when doing:

int main()
{
getch();
}

I can't find the link but supposedly the problem is, it needs to turn off buffering or something strange along those lines and I still want cout to work along with cross platform code.

I was told to use std::cin.get(), but I'd like the app to quit when a key is pressed, not when the user typed in a letter or number then press enter to quit.

Is there any function for this? The code must work under Mac (my os) and Windows.

+1  A: 

You have not exhibited a

#include <stdio.h>

or

#include <curses.h>

or similar line. Are you sure that you are linking against a library that includes getch()?

dmckee
A: 

linking/compiling is not an issue, i include curses and do -lcurses in xcode. window uses conio.h

acidzombie24
This should be a comment to the dmckee answer, NOT an answer in its own right. This is because the order of answers will change with voting.
paxdiablo
+6  A: 

Have you looked in <curses.h> to see what the getch() function does?

Hint: OSX and Linux are not the same as Windows.

Specifically, as a macro in <curses.h>, we find:

#define getch() wgetch(stdscr)

Now, there appears, on your system, to be an actual function getch() in the curses library, but it expects stdscr to be set up, and that is done by the curses initialization functions (initscr() and relatives), and that is signally not done by your code. So, your code is invoking undefined behaviour by calling curses routines before the correct initialization is done, leading to the crash.

(Good hint from dmckee - it helped get the link line out of acidzombie24, which was important.)

To get to a point where a single key-stroke can be read and the program terminated cleanly, you have to do a good deal of work on Unix (OSX, Linux). You would have to trap the initial state of the terminal, arrange for an atexit() function - or some similar mechanism - to restore the state of the terminal, change the terminal from cooked mode into raw mode, then invoke a function to read a character (possibly just read(0, &c, 1)), and do your exit. There might be other ways to do it - but it certainly will involve some setup and teardown operations.

One book that might help is "Advanced Unix Programming" by Mark Rochkind; it covers terminal handling at the level needed. Alternatively, you can use <curses.h> properly - that will be simpler than a roll-your-own solution, and probably more reliable.

Jonathan Leffler