xstring 在 0x1005E5F6 (ucrtbased.dll) 抛出未处理的异常

xstring throwing unhandled exception at 0x1005E5F6 (ucrtbased.dll)

我正在使用最新版本的 Visual Studio Community 2017 在 Windows 8.1 的更新版本上学习 C++。

当我调整以下 .cpp 文件和 运行 程序时,它在输入错误后崩溃:

Debug Assertion Failed!

Program C:\WINDOWS\SYSTEM32\MSVCP140D.dll File c:\program files (x86)\microsoft visual studio17\community\vc\tools\msvc.11.25503\include\xstring Line: 2969

Expression string subscript out of range

#include "stdafx.h"
#include "FBullCowGame.h"

using int32 = int;

FBullCowGame::FBullCowGame() { Reset(); }

int32 FBullCowGame::GetMaxTries() const { return MyMaxTries; }
int32 FBullCowGame::GetCurrentTry() const { return MyCurrentTry; }

void FBullCowGame::Reset()
{
    constexpr int32 MAX_TRIES = 8;
    MyMaxTries = MAX_TRIES;

    const FString HIDDEN_WORD = "ant";
    MyHiddenWord = HIDDEN_WORD;

    MyCurrentTry = 1;
    return;
}


bool FBullCowGame::IsGameWon () const { return false; }

bool FBullCowGame::CheckGuessValidity(FString)
{
    return false;
}
// Receives a VALID guess, increments turn, and returns count

FBullCowCount FBullCowGame::SubmitGuess(FString Guess)
{
    // incriment the turn number
    MyCurrentTry++;

    // setup a return variable
    FBullCowCount BullCowCount;

    // loop through all letters in the guess
    int32 HiddenWordLength = MyHiddenWord.length();
    for (int32 i = 0; i < Guess.length(); i++) {
        // compare letters against the hidden word
        for (int32 j = 0; j < HiddenWordLength; j++) {
            // if they match then
            if (Guess[j] == MyHiddenWord[i]) {
                if (i == j) { // if they're in the same place
                    BullCowCount.Bulls++; // incriment bulls
                }
                else {
                    BullCowCount.Cows++; // must be a cow
                }
            }
        }
    }
    return BullCowCount;
}

调试时,它把我带到了 xstring 中引用的行,它给出了以下错误:

Unhandled exception at 0x1005E5F6 (ucrtbased.dll) in BullCowGame.exe: An invalid parameter was passed to a function that considers invalid parameters fatal.

代码:

    reference operator[](const size_type _Off)
    {   // subscript mutable sequence
    auto& _My_data = this->_Get_data();
    _IDL_VERIFY(_Off <= _My_data._Mysize, "string subscript out of range");
    return (_My_data._Myptr()[_Off]);
    }

我做的事情似乎触发了断点,但代码反映了教程中的代码并且教程代码正确编译和运行。

有人知道怎么处理吗?我在搜索时一无所获。

这看起来很可疑:

for (int32 i = 0; i < Guess.length(); i++) {
    // compare letters against the hidden word
    for (int32 j = 0; j < HiddenWordLength; j++) {
        ...

注意,i受猜测长度限制,j受HiddenWord长度限制

请注意,您在此处混淆了索引变量:

        // if they match then
        if (Guess[j] == MyHiddenWord[i]) {

此外,无论如何您都应该查看这一行,因为异常出现在运算符 [] 中,并且这是您发布的代码中唯一使用相关运算符的地方...:)