Is there a way to block cin input for a certain time and then allow input again?

305 views Asked by At

I am writing a text based game in which messages to the terminal are printed by sleeping for a few milliseconds between each character, and then input is taken from the player like so:

#include <iostream>
#include <unistd.h>
#include <climits>
int main() {
    std::string line;
    std::string message = "LotsAndLotsAndLotsAndLotsAndLotsAndLotsAndLotsAndLotsAndLotsAndLotsAndLotsAndLotsAndLotsAndLotsAndLotsAndLotsOfText\n";
    for(char c : message) {
        usleep(1000 * 40);
        std::cout << c << std::flush;
    }

    std::getline(std::cin, line);
    std::cout << line << "\n";

    return 0;
}

The problem is that if the player types anything while the message is being printed, getline will pick it up.

I can't use cin.ignore because I don't know how many characters or what type of characters the player might enter while waiting for the message. Is there a way to get around this?

2

There are 2 answers

0
cluemein On

This is partly a speculative answer, as I have not actually tested this. It may be possible to make a loop that blocks other parts of your code from executing until the loop is complete, where this loop runs until you have finished the message. This loop would use a parameter/flag such as eof or maybe (I forget if this is actually possible) something like an end-of-line message. At the same time, you could make the code for getting input be part of a separate method, so that method is only called when you want it to be called.

0
Phoned_Leek25 On

A possible solution if you're running this in Win32 or basically a console app is to make use of the system() function, specifically system("pause"). Try this:

#include <iostream>
#include <string> //required for getline
#include <Windows.h> //required for Sleep()
//#include <climits> //not needed.

int main() {
    std::string line;
    std::string message = "LotsAndLotsAndLotsAndLotsAndLotsAndLotsAndLotsAndLotsAndLotsAndLotsAndLotsAndLotsAndLotsAndLotsAndLotsAndLotsOfText\n";
    for (char c : message) {
        //usleep(1000 * 40);
        Sleep(10); //in miliseconds.
        std::cout << c << std::flush;
    }
    system("pause");
    std::cout << "resumed listening.\n";
    std::getline(std::cin, line);
    std::cout << line << "\n";
}