Saladin Akara
Saladin Akara

Reputation: 2548

Using kbhit() to pause terminal output?

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.

Upvotes: 1

Views: 977

Answers (2)

please delete me
please delete me

Reputation:

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);

Upvotes: 2

You
You

Reputation: 23814

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();
}

Upvotes: 2

Related Questions