错误字符串下标超出范围c ++

时间:2015-03-18 21:34:59

标签: c++ loops

我有一个猜对手的名字游戏。我有这个功能的问题。在嵌套循环中,如果用户输入了错误的字母,它会给我这个错误:

行:1440 表达式:字符串下标超出范围

这是功能:

void Play(int selection, int FArraySize, int  MArraySize,string Female[], string Male[])//Receive the selected name category array and its size and implements the game logic as shown in the sample run. Uses function GetRandomName(…).
{
    int MAX_TRIES = 4;
    int m = 0;
    int x=0;
    int j=0;
    ofstream ofFile;
    ifstream InFile;
    int num_of_wrong_guesses=0;
    char letter;
    string GuessedName;
    GuessedName = GetRandomName(selection, FArraySize, MArraySize, Female, Male);

    cout << "Guess the following name:" << endl;


    for(int y = 0; y < GuessedName.length(); y++){
        cout << "?";
        j++;
    }

    cout << "\nEnter a guess letter? or * to enter the entire name" << endl;
    cin >> letter;

    int i =0;

    for ( int count = 0 ; count <= MAX_TRIES ; count++)
    {
        while (i <= j)
        {

            if (letter ==  GuessedName[i])
            {
                i = m;
                cout << letter << " exists in the name";
                cout << "\nyou have " << MAX_TRIES << " remaining guess attemps... "<< endl;
                break;
            }
            if (i == j)
            {
                cout <<"Sorry! " << letter << " dose not exist in the name";
                cout << "\nyou have " << MAX_TRIES-- << " remaining guess attemps... ";
                break;
            }
            i++;
        }

        cout << "\nGuess the following name:" << endl;
    for(int y = 0; y < GuessedName.length(); y++){
        cout << "?";
        j++;
    }
        cin >> letter;
    }
    return;
}
希望你能帮助我。

1 个答案:

答案 0 :(得分:0)

while (i <= j)应为while (i < j)

否则GuessedName[i]会在i == j时尝试访问越界。 j - 1是最后一个字母的索引。