Мой код работает нормально, но ломается во время игрового цикла - PullRequest
0 голосов
/ 19 октября 2018

Приведенный ниже код может нормально работать в отладчике, но в итоге не может ничего напечатать после цикла while (некорректно), как прокомментировано внизу.После завершения функции кода или угадывания всего кода код вылетает и приводит вас к ошибке времени выполнения в файле с именем memcpy.asm.Из моих исследований люди часто считают, что этот файл связан только с отсутствием.Я помню, что мой код работал до конца в более ранней версии до добавления массива подсказок и перехода в инструменты Visual Studio-> options-> Debugger-> Symbols и проверки «Microsoft Symbol Servers», так как мой первоначальный запуск после проверкия снял галочку.

#include <iostream>
#include <ctime>
#include <cstdlib>
#include <string>

int main()
{
    std::cout << "Welcome to my Word Scramble!\nYou can quit at anytime by typing 'quit' and get a hint by typing 'hint' though this halfs your points!\n";
    srand(static_cast<unsigned int>(time(0)));
    bool gameOn = true;
    int score = 0;

    while (gameOn)
    {

        std::string word[] = { "programming","saturn","helpful","terrible","college" };
        std::string hint[] = { "Another word is coding","A planet in our solar system","to be of use","Just the worst","School for grown ups" };

        for (int i = 0;i < word->size();i++) 
        {
            std::string jumble = word[i];
            int length = jumble.size();

            for (int j = 0; j < length; j++)
            {
                int index1 = rand() % length;
                int index2 = rand() % length;
                char temp = jumble[index1];
                jumble[index1] = jumble[index2];
                jumble[index2] = temp;
            }

            std::cout << "Here is the word you'll be unscrambling!\t--" << jumble << "--\n";
            int guesses = 1;
            int pointReward = 100*length;
            std::string guess;
            bool incorrect = true;

            while (incorrect)
            {
                std::cin >> guess;
                if (guess == "quit") 
                {
                    return 0;
                }
                else if (guess == "hint")
                {
                    pointReward /= 2;
                    std::cout << "Your score for this round has been reduced by half, Here is your hint:";
                    std::cout << hint[i] << std::endl;
                }
                else if (guess == word[i])
                {
                    incorrect = false;
                    int roundPoints = pointReward / guesses;
                    score += roundPoints;
                    std::cout << "Correct!!! You get " << roundPoints << " Points!\n\nYour total score is " << score << std::endl;
                }
                else if (guess!="hint"&&guess!="")
                {
                    guesses++;
                    std::cout << "That wasn't quite it, I believe in you!\n";
                }
                std::cout << "right after else if state\n";
            }
            std::cout << "right after incorrect loop";
        }
        std::cout << "Anything after this point won't print";
        gameOn = false;
    }
    std::cout << "Your final score was " << score << "!";
    std::cout << "\tThanks For Playing My First C++ Game!";
    return 0;
}

Сообщение об ошибке консоли для кода является загадочным для меня, чтобы понять, в чем проблема:

'Word Jumble.exe' (Win32): Unloaded 'C:\Windows\SysWOW64\ucrtbased.dll'
Exception thrown at 0x509146FE (vcruntime140d.dll) in Word Jumble.exe: 0xC0000005: Access violation reading location 0xCCCCCCCC.
Unhandled exception at 0x509146FE (vcruntime140d.dll) in Word Jumble.exe: 0xC0000005: Access violation reading location 0xCCCCCCCC.

Я провел небольшое исследование, но«Место чтения нарушения доступа ...» - это плохой код, но я не вижу ничего неправильного в логике.

1 Ответ

0 голосов
/ 19 октября 2018

word->size() дает вам длину строки word[0].Однако вам нужен размер массива word[].Используйте std::size(word).

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...