Search code examples
c++ctime

Can't time input: C++


I am trying to make a game to test my C++ skills, and in the game I created a class called Player with the method function definition attack(). It prints a random string based on a Player method variable, and then it asks the player to input that string in as little time as possible:

//definitions for Player
int Player::attack()
{
     std::cout << "You are now attacking. \n";
     std::cout << "You must enter this string in as little time as possible:";

     std::string r = randStr(wordc);
     std::cout << r << "\n";

     std::string attack;
     double seconds_since_start;
     time_t start = time(0);
     while (true)
     {
          std::cin >> attack;
          if (attack == r) {break;}
          seconds_since_start = difftime(time(0), start);
     }
     std::cout << "You typed the word in " << seconds_since_start << "seconds\n";
}

It doesn't work, and I have looked everywhere for an answer. It just returns random numbers that don't make sense. When I see people using the difftime() function, they always convert a tm structure to a time_t variable and then put it as the second argument. Do you need to use this? What type of data does the difftime() function return? What am I doing wrong? Is it the compiler? I really appreciate your help.


Solution

  • Just place the time measurement in the if block before break; and the delay will be correctly computed. But, for the next try when attack != r, you have to restart the counter (if needed).

    double seconds_since_start;
    time_t start = time(0);
    while (true)
    {
        std::cin >> attack;
        if (attack == r) {
            // stop the counter and measure the delay
            seconds_since_start = difftime(time(0), start);
            break;
        }
        // restart the counter (if needed)
        start = time(0);
    }
    std::cout << "You typed the word in " << seconds_since_start << "seconds\n";