No-wait scanf?

Hello,

I'm a C n00b. I have a simple question, how do you get "scanf" (or an equivalent) that doesn't wait for the user's input (or waits a specific amount of time)? What I want to do is simple. I want my program to print numbers 1 to 5 and 4 to 1 while waiting 1 second / the current number (e.g. 0.2 seconds for the number 5). I hope to eventually use this program in a game but I'm too much of a beginner ATM so I'm still learning. Here's the actual code (I do know this is Objective C commands but I figured it's still a C++ problem):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#import <Foundation/Foundation.h>
#import <Cocoa/Cocoa.h>
#include <stdio.h>
#include <time.h>

char mystop;

void mysleep(float fseconds)
{
	clock_t goal = (fseconds * CLOCKS_PER_SEC) + clock();
	while (goal > clock()){
        DO NOT WAIT FOR USER BUT GET IMPUT HERE (I think)
}	
}

int main (int argc, const char * argv[]) {
	
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
	
	NSLog(@"To stop the timer, press enter (5 is the best).");
	
	for (int i = 1; i <= 5; i++) {
	NSLog(@"%i\n", i);
	mysleep(1.0/i);
	
	}
	
	for (int i = 4; i >= 1; i--) {
		NSLog(@"%i\n", i);
		mysleep(1.0/i);
	}
	
	[pool drain];
	return 0;
}


The "mystop" char is hopefully going to get the input to stop the countdown.

Thanks in advance for the help, maybe it's obvious but I can't find the answer by Googling it (maybe it's just me)!

-Guy
Also I realize that the waiting could be done in a more effective way (other than running in an empty loop) but the main concern is the scanf without waiting for user input.
I don't think any of the functions in the C standard library can get user input in a non-blocking manner. You'd have to either use a game programming library like SDL or get events from the windowing system. Then the code would be structured like
1
2
3
4
5
6
7
8
9
10
11
12
while (!event_queue_is_empty()){
    Event e=pop_an_event();
    switch (e.type){
        //...
        case KEYBOARD_EVENT:
            switch (e.keyboard_event.key){
                //...
            }
            break;
        //...
    }
}
Topic archived. No new replies allowed.