我是编码的新手,我试着写一个刽子手游戏。程序随机选择10个单词中的一个,仅显示“_”,每次猜测后屏幕都会刷新。
问题是有时循环显示整个屏幕的2倍。所以,我尝试使用 -
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
然后Visual告诉我程序触发了一个断点。有什么问题?
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;
void showLogo();
int main()
{
int number, amount;
int mistake = 5;
int wrongLetter = 0;
char letter;
char tab[13];
char unknown[13];
char usedLetters[5];
char *wsk;
srand(time(NULL));
number = rand() % 10; //choose one of 10 words
string words[10] ={"LONGITUDINAL","UNFORTUNATELY","EXPLANATORY",
"PERENNIAL","UNPUTDOWNABLE","REMORSELESS",
"INTERMITTENT","ADJUDICATE","INERSTITIAL",
"MALPOSED" };
amount = size(words[number]);
strcpy_s(tab, words[number].c_str()); //string to char
for (int i = 0; i < amount; i++)
{
unknown[i] = '_';
}
while (mistake)
{
int noOfGuessed = 0;
showLogo();
cout << "You have: " << mistake << " chances." << endl << endl;
cout << "Used words: ";
for (int i = 0; i < wrongLetter; i++)
{
cout << usedLetters[i] << " ";
}
cout << endl << endl;
for (int i = 0; i < amount; i++)
{
cout << unknown[i] << " ";
}
cout << "\t Enter a letter: ";
letter = getchar();
letter = toupper(letter);
for (int i = 0; i < amount; i++)
{
if (letter == tab[i] && unknown[i] == '_')
{
wsk = &unknown[i];
*wsk = letter;
noOfGuessed++;
}
}
if (noOfGuessed == 0)
{
mistake--;
usedLetters[wrongLetter] = letter;
wrongLetter++;
}
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
system("cls");
}
system("pause");
return 0;
}
void showLogo()
{
cout << "\t\t\t\t\t\t\t HANGMAN" << endl;
cout << endl;
cout << endl;
cout << endl;
}
答案 0 :(得分:0)
ignore()
将设置cin的eof位,并使流处于错误状态。调用ignore()
后,应始终清除流错误位。
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
cin.clear();