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?
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.