2015-03-18 71 views
0

我有一个猜测的名字游戏。我有这个功能的问题。在嵌套循环,如果用户输入了错误的信它给了我这个错误:错误字符串下标超出范围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; 
} 

希望你可以帮我。

+0

您正在循环,直到i = j。如果与GuessedName [j]相比,这将成为第一个,这是禁用的。 – KuramaYoko 2015-03-18 21:38:44

+0

此外,打印问号的那些循环不必在那里。所有你需要的是一行:'cout << string(GuessName.length(),'?');' – PaulMcKenzie 2015-03-18 21:41:08

+0

@PaulMcKenzie我需要他们来计算j。 – 2015-03-19 04:27:31

回答

0

while (i <= j)应该是while (i < j)

否则GuessedName[i]将尝试访问超出范围时i == jj - 1是最后一个字母的索引。