views:

59

answers:

2

I took my first 'fundamentals of programming' lab session at uni today. One thing struck me as odd, though: the use of while(! _kbhit()) from conio.h (which I'm sure is a C unit?) to 'pause' the console output.

Is this the best way to do this? What do I need to watch out for when using it? Is my tutor absolutely bonkers? I only ask because it seemed like a bit of a dirty hack and I've never seen it before in any of the C++ code snippets I've looked at.

Marked question as homework because it's school related, but not actually a homework task. If this question is better off as CW, let me know.

+1  A: 

Using conio.h (or worse, calling pause or similar utilities using system) is generally a bad idea; it's not very portable. Instead, one can use the capabilities of cin:

#include <iostream>
#include <limits>

/* Either of these would work, AFAIK */
void pause() {
    std::cin.ignore(std::numeric_limits<std::streamsize>::max());
    std::cin.get();
}

void pause() {
    std::cin.ignore(std::cin.rdbuf()->in_avail());
    std::cin.get();
}

void pause() {
    std::cin.sync();
    std::cin.get();
}
You
+2  A: 

A very quick (and easy to remember) way of doing this is to use getchar:

getchar();

You may have to press Return after entering your char, depending on stdin's buffering mode. You can probably use setvbuf to fix that, but personally I just always press Return.

You may also be using C++ iostreams. In that case, you'll want to call this somewhere:

std::ios::sync_with_stdio(true);
brone
The difference being that calling `getchar` consumes a character from `stdin`, whereas calling `_kbhit` doesn't, it just tells you whether the console input is ready for reading (and avoids buffering, I think). Which isn't to say that busy-looping is a good idea, or that the functional difference necessarily matters.
Steve Jessop
`fflush(stdin)` invokes Undefined Behaviour.
Prasoon Saurav
Removed reference to fflush -- thanks. (Don't ask me why I started doing that; I've been using this code snippet for more than 10 years...)
brone
As for the difference between getchar and kbhit, you're right that if you're using stdin for something, you're stuck. Not much you can do about this if you're trying to code to the standard, I don't think...
brone