C++程序在执行时停止响应

C++ program stops responding on execution

本文关键字:响应 执行 程序 C++      更新时间:2023-10-16

有关我的计算机的基本信息:Windows 7 x64操作系统
8gb内存
使用MingW编译器

所以,每次我在编译完程序后通过终端运行程序时,它都会立即停止响应。我自己似乎找不到这个问题,所以我需要一双额外的眼睛来帮我指出。我现在实际上是C++的初学者,所以请耐心等待。

    #include <iostream>
    #include <cstdlib>
    #include <string>
    #include <vector>
    #include <ctime>
    using namespace std;
int main()
{   
    bool correct = false;
    srand(time(NULL));  
    vector<string> guess;
    vector<string> pallete;
    vector<string> secret;
    pallete.push_back("red");
    pallete.push_back("green");
    pallete.push_back("blue");
    pallete.push_back("yellow");
    for(int i = 0; i < 4 ; i++)
    {
        secret.push_back(pallete.at(rand()%secret.size()));
    }
    for(int j = 0; j < 4 ; j++)
    {
        guess.push_back(pallete.at(rand()%guess.size()));
    }
    vector<string> secretMem = secret;
    cout << "the guess was:";
    for(int x = 0; x<4; x++)
    {
        cout << guess[x] << endl;
    }
    while(correct == false)
    {
        int blackP = 0; 
        int whiteP = 0;
        secret = secretMem;
        for (int idxB = 0; idxB < secret.size(); idxB++)
        {
            if (guess[idxB] == secret[idxB])
            {
                secret[idxB] = "0";
                guess[idxB] = "1";
                blackP++;
            }
        }   
        for (int idxW = 0; idxW < secret.size(); idxW++)
            for (int idyW = 0; idyW < guess.size(); idyW++)
            {
                if (secret[idxW] == guess[idyW])
                {
                secret[idxW] = "0";
                guess[idxW] = "1";
                whiteP++;
            }
        }
        if (blackP == 4)
        {
            cout << "Congratulations you win." << endl << "The secret code was:"<< endl;
            for(int y = 0; y<4; y++)
            {
                cout << secretMem[y] << endl;
            }
            correct = true;
        }
        else
            cout << "you scored: " << blackP << " Black pegs" << "and" << whiteP << " White pegs" << endl;
    }
    return 0;
}

此外。。。。这种糟糕的代码格式是怎么回事。。。。我只是无法像写预览时那样在预览中正确排列…

除以零?secret.size()最初为0。

secret.push_back(pallete.at(rand()%secret.size()));

您正在除以零。

在您的行secret.push_back(pallete.at(rand()%secret.size()));中,secret.size()为零。根据前面这个问题的答案,Mod 0是"未定义的,可能会抛出‘除以零’异常。"

如果你试图选择一个介于0和最大潜在颜色数之间的数字来猜测,我可能会把这行改为secret.push_back(pallete.at(rand() * pallete.size()-1 ))

我想你指的是两个位置的pallete.size(secret.size,guess.size)。然后你有一个无限循环,因为blackP从来都不是4,每个循环都做同样的事情,因为secretMem从来没有更新过。也许在Windows上,它能够处理溢出(不知怎么的?),但却陷入了循环。尽管在这种情况下,你会得到很多"你得分了:0个黑色钉子和1个白色钉子"的线条。