while循环使用c ++中的计时器

Joe*_*eah 1 c++ loops while-loop

我正在尝试创建一个while循环,当满足字符串条件或计时器条件时,程序将跳出循环并打印出所需的输出.当打印出所需的输出时,输出将包含比较答案之前和之后的时间差.

但是循环并没有像我期望的那样运行.所以任何人都可以帮我弄清楚这段代码的问题在哪里?

以下是我的代码:

void startGame(time_t cd,int gl){
    string guessWord;
    time_t start, end, diff,timeLeft;

    cout << "Scrambled word is " << randomizeWord(gl) << endl;

    while (timeLeft != cd || guessWord.compare(originalWord) == 0)
    {
        start = time(0);
        cout << "You have " << cd << " seconds to guess." << endl;
        cout << "Enter guess : ";
        cin >> guessWord;
        end = time(0);
        diff = end - start;
        //total_time = total_time + diff;
        timeLeft = cd - diff;

        if(guessWord.compare(originalWord) != 0)
        {
            cout << "WRONG! Attempt ... You have " << timeLeft << "seconds left... Try Again" << endl;
            cout << "Enter guess : ";
            cin >> guessWord;             
        }
        else
        {
            cout << "You are CORRECT! "<< timeLeft <<" seconds left. Your timing is "<< diff <<" seconds." << endl;            
            break;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*ork 5

条件说明

也改变你的循环条件:

while ((timeLeft <= cd) && (guessWord.compare(originalWord) != 0))
Run Code Online (Sandbox Code Playgroud)

如果其中一个条件失败,您将爆发.这是因为&&如果任一条件失败,则结果为false.因此,当a)你有时间离开而b)你没有猜到这个词的时候,这将继续下去.你的使用||将使循环继续,而其中任何一个为真(因此两个都必须失败,循环退出).

Note:我个人认为额外的大括号()很好听,使表达更具人性化.对于没有经验的程序员,他们不需要按优先顺序猜测(查找)

剩余时间计算:

time_t start    = time(0);  // Make the start time absolute and outside the loop.
                            // Note: Use one line per variable declaration and initialize.
int    timeLeft = cd;       // timeLeft is a relative value that can be negative => `int`

// Notice I adjust timeLeft because of new definition.
while ((timeLeft > 0) && (guessWord.compare(originalWord) != 0))
{
    time_t end       = time(0);
    time_t timeTaken = end-start;        // Total time taken so Far.
    timeLeft         = cd - timeTaken;   // Time left is thus.
Run Code Online (Sandbox Code Playgroud)