Input does not enter buffer when sleeping

When the program is processing/sleeping, those char input at that time would not goes into the buffer until the next input request (such as calling istream::get). The program below shows this.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <streambuf>
#include <chrono>
#include <thread>

int main() {
    std::cout << "Sleeping...\n";
    std::this_thread::sleep_for(std::chrono::seconds(3));
    // something is input while sleeping 
    // (but the terminal does not show)
    std::cout << "wake up!\n";
    std::streambuf* pbuf = std::cin.rdbuf();
    std::streamsize size = pbuf->in_avail();    // always 0
    std::cout << size << " characters in buffer\n";

    std::cout << "Input something: ";
    std::cin.get();  // what I have input previously would show now
    std::cin.unget();
    size = pbuf->in_avail();    // non-zero
    std::cout << size << " characters in buffer\n";
}


I wonder if there is a way to distinguish between the input comes from the time that does not request it (i.e., during processing or sleeping) and those comes after the time does request it (in the example, after "Input something: ").
Last edited on
It's a little difficult to understand the question but I think I get what you're asking. C++ streams do not have time stamps. You can safely assume that the stream stack is "first in first out" so, unless something funny is going on, the data will get to you in the order that it arrived on the stream.
I wonder if there is a way to distinguish between the input comes from the time that does not request it


The short answer is "no". At least not with the STL console functions.

If you're not requesting input, then any input the user supplies is discarded (or, in this case, postponed until you actually request it).

Why would you need to do this anyway?
C++ streams do not have time stamps.
What are time stamps? Does other languages have them?

The short answer is "no".
Oh :(

Why would you need to do this anyway?
I created a reaction game written in C++. I have no way to know if the reaction (pressing enter) is made accordingly, or made at the time the user is waiting.
Topic archived. No new replies allowed.