Привет, я попытался создать свой код, но он выдал исключение, может ли кто-нибудь помочь мне решить его? ниже приведены коды и выходные данные.C++ terminate call после вызова экземпляра 'std :: out_of_range' what(): vector :: _ M_range_check
Благодаря
int main()
{
char input;
while (input!= 'g')
{
cout << "Welcome to my Scramble Word Game!" << endl << endl;
cout << "a) Add Words into game database" << endl;
cout << "b) Remove words" << endl;
cout << "c) configure count down time" << endl;
cout << "d) Start game" << endl;
cout << "e) Select Game level" << endl;
cout << "f) View score chart" << endl;
cout << "g) Quit" << endl;
cout << "Please enter an alphabet to select: ";
cin >> input;
cout << endl;
switch(input)
{
case 'a': cout << "Please enter word not long than 16 characters" << endl;
write();
break;
case 'b': cout << "Please enter word to remove" << endl;
cin >> delword;
removeWord(delword);
break;
case 'c': cout << "c) configure count down time" << endl;
break;
case 'd': cout << "Game Started" << endl;
startGame(sl);
break;
case 'e': cout << "PLease select Game level" << endl;
cin >> sl;
break;
case 'f': cout << "f) View score chart" << endl;
break;
case 'g': cout << "g) Quit" << endl;
break;
default: cout << "Invalid selection, please enter a alphabet"
<< " from the entrees above.\n\n";
break;
}
}
return 0;
}
void removeWord(string r)
{
ifstream wordBase("Words Database.txt",ios::out);
ofstream temp ("temp.txt");
string line = "";
while(getline(wordBase,line))
{
if(line != r)
temp << line << endl;
}
temp.close();
wordBase.close();
remove("Words Database.txt");
rename("temp.txt","Words Database.txt");
}
int write(void)
{
ofstream outfile;
string userInputOfWord;
outfile.open("Words Database.txt" ,ios::app);
cin.clear();
cin >> userInputOfWord;
outfile << userInputOfWord << endl;
outfile.close();
cout << "Word entered into database" << endl << endl;
return 0;
}
void startGame(int sl)
{
{
int sl;
string word;
vector<string> levelList;
srand(time(NULL));
string guess;
string words;
vector<string> wordList;
ifstream in ("Words Database.txt");
while(in >> words)
{
wordList.push_back(words);
}
for(vector<string>::iterator it = wordList.begin(); it != wordList.end(); ++it)
{
cout << *it << ' ';
switch(sl)
{
case 1 : if((*it).length() >= 2 && (*it).length() <= 7)
{
levelList.push_back(*it);
}
break;
case 2 : if((*it).length() >= 8 && (*it).length() <= 15)
{
levelList.push_back(*it);
}
break;
case 3 : if((*it).length() > 15)
{
levelList.push_back(*it);
}
break;
}
}
string jumble = levelList.at(rand()% wordList.size());
word = jumble;
int length = jumble.size();
for (int n=0;n<length;n++)
{
int index1 = (rand()%length);
int index2 = (rand()%length);
char temp = jumble[index1];
jumble[index1]=jumble[index2];
jumble[index2]=temp;
}
cout << "Scrambled word is "<< jumble << endl;
cout << "Enter guess: ";
cin >> guess;
while (guess != word)
{
cout <<"Wrong attempt ... try again";
cout << "\n\nYour guess: ";
cin >> guess;
}
if (guess == word)
cout << "\nYou are correct!\n";
else
cout << "\nThanks for playing.\n";
}
}
Добро пожаловать в мой Scramble Слово игры!
а) Добавить слова в базу данных игр б) Удалить слова с) настроить отсчет время d) Запустить игру е) Выберите уровень игр х) Посмотреть оценку диаграмма г) Выход Пожалуйста, введите алфавит выберите: d
игры Начало Terminate называется кинув экземпляр 'станд :: out_of_range' , что(): вектор :: _ M_range_check яблоко апельсин арбуз lemondinosaur RUN ЗАВЕРШЕНА; Отменено; в реальном времени: 1 с; user: 0ms; Система: 0ms
На этой линии 'строки перемешивать = levelList.at (RAND()% wordList.size()); ', вы делаете предположение, что размер' levelList' и размер 'wordList' одинаковы. Вы должны проверить это предположение. –
@ Vaughn Cato, levelList - это возможность получить слова из списка слов в соответствии с их размером и распределить их в соответствующих случаях. –
@WilsonTurner: простой 'std :: cout << levelList.size() <<" "<< wordList.size();' прямо перед 'string jumble = levelList.at (rand()% wordList.size()), 'сразу скажу вам, в чем проблема. –