[英]error string subscript out of range c++
我猜過一個名字游戲。 我對此功能有疑問。 在嵌套循環中,如果用戶輸入了錯誤的字母,則會出現此錯誤:
行: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;
}
希望您能夠幫助我。
while (i <= j)
應該是while (i < j)
。
否則,當i == j
時, GuessedName[i]
將嘗試訪問越界。 j - 1
是最后一個字母的索引。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.