How would one listen for keyboard input, without causing the program to pause waiting for the input? For instance say you have something like

float num = 0;
bool runloop = true;
for(int i=0; i<1000000 && runloop; i++{
	n += some_time_consuming_transformation(i);
	// How to listen for input at this point? e.g. waitforoptionalinput() function
}
printf("n is %d\n", n);

And you want it to run indefinitely unless the user enters some key, say "q". And if the user enters "q" it would call some other function, similar to

function verify(){
	printf("Are you sure you want to stop here? (y/n)\n");
	char y_or_n[1];
	cin >> y_or_n;
	if(strcmp("y",y_or_n)==0 || strcmp("Y",y_or_n)==0) runloop = false;
}

Also, would there perhaps be a way to in advance tell the program to listen for keyboard input at any point - without explicitly calling a waitforoptionalinput() at a certain point in the program.

You can use the GetAKeySyncState() function from windows.h.

Thanks, but what about for Linux?

I also couldn't find any references or docs online for GetAKeySyncState(), and when I try to compile (after including windows.h) on my Windows machine I get

error: 'GetAKeySyncState' was not declared in this scope".

Its been a while since I used it, but I'm pretty sure it grabs the current key being pressed down and returns its value(was for making a tetris game in class, I can't say I knew all that much back then). As for linux, you can disable the input buffer for cin(or something along the lines of this), which isn't really recommended. Alternatively you can run it on a seperate thread.

Alternatively you can run it on a seperate thread.

That would be my first suggestion. You could also think about using pipe()/fork() and have one process listen for messages while the rest of your program executes.

I also couldn't find any references or docs online for GetAKeySyncState(), and when I try to compile (after including windows.h) on my Windows machine I get

In Win32 it's GetAsyncKeyState() or GetKeyState().

GetAsyncKeyState(32) will return non zero if key 32(which happens to be spacebar) is pressed.
if spacebar is not being pressed then it returns 0. this runs in the background and the console does not have to be the active window to receive input. it also does not make the console wait for the key to be pressed. to make it wait for that key you could do:
do{}while(!GetAsyncKeyState(32))

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.