0

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.

Chopdops
  • 11
  • 1
  • 8
  • 1
    You can find some documentation for `difftime()` [here](http://en.cppreference.com/w/cpp/chrono/c/difftime). But for C++ you should prefer [`chrono`](http://en.cppreference.com/w/cpp/header/chrono). – wally Nov 10 '16 at 14:55
  • May be you should try with the example as is given in the [reference documentation](http://en.cppreference.com/w/c/chrono/difftime). – πάντα ῥεῖ Nov 10 '16 at 14:55
  • 6
    If the user enters the correct string on the first try, you break out of the loop without ever setting `seconds_since_start`. Even if the user doesn't, you still don't include the last, successful attempt into the measurement. Move `seconds_since_start` assignment to the point right after the loop. – Igor Tandetnik Nov 10 '16 at 14:55
  • learn to step through your code wiht a debugger, inspecting the important variables as you go – pm100 Nov 10 '16 at 16:50

1 Answers1

0

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";
J. Piquard
  • 1,665
  • 2
  • 12
  • 17