0

I want to create a code snippet which waits for some time (say 3 seconds) if you give
input....fine
But if you didn't give input in 3 seconds, the variable should fetch some default value (set by us).

How can I make such a snippet ?

1 Answers1

2

Maybe this code help :

#include <iostream>
#include <thread>
#include <chrono>

int getVal(int defaultValue)
{
    int val=0;
    std::thread t1([&](){
        std::cin>>val;
    });
    std::this_thread::sleep_for(std::chrono::seconds(3));
    t1.detach();

    if(val==0)
        val=defaultValue;
    return val;
}

int main()
{
    std::cout<<getVal(123);
}
uchar
  • 2,552
  • 4
  • 29
  • 50