【发布时间】:2013-11-26 02:57:33
【问题描述】:
过去两天我一直在尝试修复这个程序,但事实证明它很麻烦。这是我的 C++ 课程介绍的作业,除了麻烦之外什么也没给我。我搜索了这个版块,发布在 Cplusplus.com 上,并在 Google 上花费了数小时,寻求帮助。
这是我的问题。我收到了一个程序,需要向它添加一些功能:
- 我必须保存用户条目。
- 如果用户两次输入相同的条目,我必须显示错误消息。
看起来很简单?不适合像我这样的初学者。这是代码,我尝试添加代码以满足问题的要求。
int main()
{
//declare variables
string origWord = "";
string letter = "";
char dashReplaced = 'N';
char gameOver = 'N';
int numIncorrect = 0;
string displayWord = "-----";
string letterGuess[26];
//get original word
do //begin loop
{
cout << "Enter a 5-letter word in uppercase: ";
getline(cin, origWord);
} while (origWord.length() != 5);
//clear the screen
system("cls");
//start guessing
cout << "Guess this word: " <<
displayWord << endl;
while (gameOver == 'N')
{
cout << "Enter an uppercase letter: ";
cin >> letter;
//Entry Storage and Error Message. This is my problem.
for (int x = 0; x < 26; x++)
{
letterGuess[x] = letter;
for (int i = x; i < 26; i++)
{
if (i != x)
{
if (letterGuess[x] == letterGuess[i])
{
cout << "Letter already entered. Choose another letter."
<< endl;
}
}
}
}
//search for the letter in the original word
for (int x = 0; x < 5; x += 1)
{
//if the current character matches
//the letter, replace the corresponding
//dash in the displayWord variable and then
//set the dashReplaced variable to 'Y'
if (origWord.substr(x, 1) == letter)
{
displayWord.replace(x, 1, letter);
dashReplaced = 'Y';
} //end if
} //end for
//if a dash was replaced, check whether the
//displayWord variable contains any dashes
if (dashReplaced == 'Y')
{
//if the displayWord variable does not
//contain any dashes, the game is over
if (displayWord.find("-", 0) == -1)
{
gameOver = 'Y';
cout << endl << "Yes, the word is "
<< origWord << endl;
cout << "Great guessing!" << endl;
}
else //otherwise, continue guessing
{
cout << endl << "Guess this word: "
<< displayWord << endl;
dashReplaced = 'N';
} //end if
}
else //processed when dashReplaced contains 'N'
{
//add 1 to the number of incorrect guesses
numIncorrect += 1;
//if the number of incorrect guesses is 10,
//the game is over
if (numIncorrect == 10)
{
gameOver = 'Y';
cout << endl << "Sorry, the word is "
<< origWord << endl;
} //end if
} //end if
} //end while
system("pause");
return 0;
} //end of main function
我对该程序的唯一编辑是直接在条目存储和错误消息的标题下。我尝试了一个 for 循环,但它只是显示输入的每个字母的错误消息。不仅如此,它还显示了 26 次。添加一个 Break 命令修复了这个问题,它只显示一次。但是,它仍然显示在每个条目上。
Cplusplus 的一名成员指出,我错误地针对同一位置的数组测试了同一变量。这就是为什么它在每个条目上都显示错误。现在有了这个循环,错误只会在输入两次时显示。但是,错误消息再次显示全部 26 次。最重要的是,只有字母一个接一个地输入才会出错。
例如,如果我输入 A,然后输入 X,然后再输入 A,则不会显示错误。如果我输入,A 然后 A 再次,错误显示 26 次。在导致错误消息多次显示的任何内容之上如何将字母变量输入到数组中的方式显然有问题。
我们将不胜感激任何数量的帮助。
编辑:我的教授已经回复我并建议使用以下内容而不是我一直在修补的内容:
for (int x=0; x<5; x++)
if (origWord[x] == letterEntered)
origWord[x] = '-';
只有我一个人,还是这完全不符合标准?我没有尝试将它转换为我的程序,因为简单的复制和粘贴作业会产生编译错误。但是,我看不出这对我正在尝试做的事情有什么作用。
【问题讨论】:
-
如果您适当地使用
std::set来管理猜测的字母,那么相当大的部分代码会消失。 -
遗憾的是,我不知道集合和向量。我已经看到它们在类似的程序中使用,但我不理解它们。我根据教授的一些意见编辑了上述内容,但似乎没有任何帮助。仍在重新思考算法。