How do I timeout when waiting for user input?

Posted on 2005-04-08
Last Modified: 2008-02-01

I'd like to ask the user a question on a console application, but I'd like a default ansnwer which will get executed if there in no answer.  I will be using cin and cout.

Question by:ba272
    LVL 55

    Accepted Solution

    I think you can use cin.peek() function to fetch if a character has ben input before calling getline()

    Something like

    #define TIMEOUT 30  // seconds

    bool isTimeout = true;
    time_t t = time(null) + TIMEOUT;   // will require time.h
    while (time(null)<t) {
        if (cin.peek()!=EOF) {
            isTimeout = false;

    if (!isTimeout) {
         // use getline or other input method
    } else {
         // Print error message

    Author Comment


    Featured Post

    Free Trending Threat Insights Every Day

    Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

    Join & Write a Comment

    Unlike C#, C++ doesn't have native support for sealing classes (so they cannot be sub-classed). At the cost of a virtual base class pointer it is possible to implement a pseudo sealing mechanism The trick is to virtually inherit from a base class…
    Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
    The goal of the video will be to teach the user the difference and consequence of passing data by value vs passing data by reference in C++. An example of passing data by value as well as an example of passing data by reference will be be given. Bot…
    The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.

    734 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    23 Experts available now in Live!

    Get 1:1 Help Now