0

I want to know how I can create a countdown that can be stopped when the user inputs something such as writing a specific sentence.

In my case I want to do something like a 'Simon says' game. Simon says 'UP' and so you have to type in UP within a time limit of two seconds. If you type anything that is not 'UP' the countdown stops and it prints out that you fail whilst if you do type 'UP' it breaks the countdown and says you win. You are also notified that you fail when the countdown reaches zero and you haven't typed anything.

Here's what I've written so far:

#include <iostream>
   #include <string>
   #include <cmath>
   #include<windows.h>
   using namespace std;


int main() {
    string answer;
    int success = 0;
    int counter = 0;

    cout << "Simon says: UP" << endl;

    for (int i = 2; i > 0; i--) {

        cin >> answer;
        if (answer == "UP") {

            cout << "You win" << endl;
            break;

        }
        else {

            cout << "You lose" << endl;

        }

     }

    return 0;

}
Alex
  • 1
  • 2
  • Please have a look at this [C++ books](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) list. – Ron Nov 13 '17 at 22:58

1 Answers1

1

Without going into multithreading, you could try _kbhit(), the non-blocking way of reading user input in combination with _getch(), both are in conio.h

#include <iostream>
#include <string>
#include <chrono>
#include <conio.h>

int main()
{

    int timeout = 2; //2 seconds

    std::string answer, say = "UP";

    std::cout << "Simon says: " << say << std::endl;
    std::cout << "You say: ";

    // get start time point
    std::chrono::system_clock::time_point start = std::chrono::system_clock::now();
    do 
    {
        if (_kbhit()) // check user input
        {
            char hit = _getch(); // read user input
            std::cout << hit; // show what was entered

            if (hit == 13)
                break; // user hit enter, so end it

            answer += hit; // add char to user answer
        }
    } 
    while (std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock::now() - start).count() < timeout);

    // check if provided answer matches

    if (answer == say)
        std::cout << "\nYou win!" << std::endl;
    else 
        std::cout << "\nYou lose!" << std::endl;

    return 0;
}

enter image description here

Killzone Kid
  • 6,171
  • 3
  • 17
  • 37