c++clock

C++ issue with sleep and srand


I wanted to make a simple program where the user has to enter a prompted number(1-4). Where the conditions of continuing is based on entering the number in the amount of time as defined by which level the user has selected and, of course, entering the correct number. The problem is that the program recognizes if the number is correct, however you can take as long as you like and it won't stop the game. This "15 minute" program was supposed to be a delve back into C++, however it has turned into a weekend long project of confusing clock algorithms and confusion. Below is the entire source code. Any help would be great...

#include <iostream>
#include <time.h>
#include <ctime>
#include <unistd.h>


using namespace std;

int main() {

    //input
    string numberGuessed;
    int intNumberGuessed;
    int score = 0;
    int actualNumber;
    int gameOver = 0;

    //Level Select Variables
    char level = {0};
    string input = " ";
    double timeForInput;


    //initialize random seed
    srand (time(NULL));


    //Generates random number
    actualNumber = rand() % 4 + 1;

    //LEVEL SELECTOUR
    cout << "Select A Level: 'e' 'm', or 'h':  ";
        getline(cin, input);

        if (input.length() == 1) {
            level = input[0];
        }

        if (level == 'e') {
            cout << "You Have Selected Easy..." << endl;
            cout<< "You Have .5 Second to Enter" << endl;
            timeForInput = 5;

        } else if(level == 'm'){
            cout << "You Have Selected Medium..." << endl;
            cout<< "You Have .2 Seconds to Enter" << endl;
            timeForInput = 2;

        } else if(level == 'h'){
            cout << "You Have Selected HARD!!!" << endl;
            cout<< "You ONLY Have .1 Seconds to Enter" << endl;
            timeForInput = 1;

        } else {
            cout << "You LOSE! GOOD DAY SIR!" << endl;
        }

        //Instructions and Countdown
        cout<<"Press The Number and Hit Enter in The Amount of Time Provided"<<endl;
        sleep(1);
        cout<<"3"<<endl;
        sleep(1);
        cout<<"2"<<endl;
        sleep(1);
        cout<<"1"<<endl;
        sleep(1);
        cout<<"GO!"<<endl;
        cout<<"--------------------------------------------------------------------------------"<<endl;
        cout<< "Enter the Numbers As They Appear:"<<endl;
        cout<<endl;
        cout<<endl;
        cout<<endl;
        sleep(1);
        double duration = 0.0;




        do {
        //Procedere For Each Round

        clock_t start;
        clock_t finish;


        start = clock();
        finish = clock();

        double delay = (double)(finish-start);


        //Clock
            start = clock();

            cout<<"The number is:  "<< actualNumber<<endl;
            getline(cin, numberGuessed);
            intNumberGuessed = stoi(numberGuessed);

            finish = clock();

            double elapsed = (double)(finish-start);
            elapsed-=delay;

            duration = elapsed/CLOCKS_PER_SEC;
            cout<<duration<<endl;

            //Test User's input
            if((intNumberGuessed == actualNumber) && (duration <= (timeForInput/10))){
                score += 1;
                gameOver = 0;

            } else if ((intNumberGuessed != actualNumber) || (duration >= (timeForInput/10))) {
                gameOver = 1;
            }

            //Reset Number
           actualNumber = rand() % 4 + 1;

        } while (gameOver != 1);


        cout<<"You Failed!"<<endl;
        sleep(1);
        cout<<"Your Score Was:  "<<score<<endl;

        return 0;

}

Solution

  • In the standard, clock() is specified to return the approximate processor time used by the process. In particular that means that the duration resulting from an expression (finish-start) doesn't necessarily equal the amount of wall-clock time that has passed. For example if you measure four threads chewing up CPU for 1 second then you should get a result of about 4 seconds.

    The way this is relevant to your program is that a program that is just waiting for input or sleeping is not using any processor time, so the result of (finish-start) will be zero.

    #include <iostream>
    
    #include <chrono>   // std::chrono::seconds, milliseconds
    #include <thread>   // std::this_thread::sleep_for
    
    #include <ctime>    // std::clock()
    
    int main() {
        auto start_processor_usage = std::clock();
        auto start_wall_clock = std::chrono::steady_clock::now();
    
        std::this_thread::sleep_for(std::chrono::seconds(1));
    
        auto finish_processor_usage = std::clock();
        auto finish_wall_clock = std::chrono::steady_clock::now();
    
        std::cout << "CPU usage: " << (finish_processor_usage - start_processor_usage) / CLOCKS_PER_SEC << '\n';
        std::cout << "Wall clock: " << (finish_wall_clock - start_wall_clock) / std::chrono::milliseconds(1) << '\n';
    }
    

    The above program should output something like:

    CPU usage: 0
    Wall clock: 1000
    

    Note that while *nix platforms in general correctly implement clock() to return processor usage, Windows does not. On Windows clock() returns wall-clock time. You need to keep this in mind when switching between Windows and other platforms.


    Ok Sure. What is the syntax for a random int using <random>? – Noguiguy

    #include <random>
    
    int main() {
      // initialize with random seed
      std::random_device r;
      std::seed_seq seed{r(), r(), r(), r(), r(), r(), r(), r()};
      std::mt19937 engine(seed);
    
      // define distribution: improved version of "% 4 + 1"
      auto one_to_four = std::uniform_int_distribution<>(1, 4);
    
      // generate number
      auto actualNumber = one_to_four(engine);
    }