我是C ++和编码的新手。我尝试制作一个子手游戏,作为一个初学者项目。我的问题是,只有按顺序键入单词的字母时,游戏才能正常工作。例如,如果单词是“ flow”,则必须连续键入每个字母(f,l,o,w)。其他任何变体均不接受,我也不知道为什么。我需要帮助调试此问题。我不确定.replace
是否是我应该在此处使用的方法。我在互联网上找到了这种方法,我认为它可以满足我的需要。
#include <iostream>
#include <string>
#include <time.h>
#include <stdlib.h>
using namespace std;
string getString(char guess) {
string s(1, guess);
return s;
}
int main() {
unsigned int seed;
int randomNumber = 0;
char guess;
string underscore;
seed = time(0);
cout << "Hangman game\n";
srand(seed);
randomNumber = (rand() % 5);
string wordList[5] = {"closet", "flow", "sheep", "see", "chocolate"};
string word = wordList[randomNumber];
int wordLength = word.length();
cout << "The word has " << wordLength << " letters\n";
for (int x = 0; x < wordLength; x++) {
underscore += "_ ";
}
cout << underscore << endl;
string holder = underscore;
for (int j = 0; j < wordLength; j++) {
cout << "\n\nType in a letter: ";
cin >> guess;
if (guess == word[j]) {
size_t found = word.find(guess);
holder.replace(found, 2, getString(guess));
cout << "\n";
word.replace(found, 1, "*");
cout << holder;
}
else {
}
}
return 0;
}
答案 0 :(得分:0)
以下一些观察可能对您有帮助:
不要在函数顶部声明所有变量。 根据需要声明它们。
避免硬编码(wordList[5]
)。根据需要在数组中添加尽可能多的字符串。使用以下内容找出数量(请参阅sizeof):
string wordList[] = { "closet", "flow", "sheep", "see", "chocolate" };
size_t wordCount = sizeof wordList / sizeof wordList[0];
您不需要手动填充 underscore
字符串。使用以下构造函数:
string underscore(word.length(), '_');
用户可以输入大写字母。将它们转换为小写。否则,您将找不到它们:
guess = tolower(guess);
您不需要精美的功能来查找输入字符的位置。 只需使用循环:
//...
bool found = true;
for (int i = 0; i < word.length(); i++)
{
if (word[i] == guess) // is the letter at position i the same as the one entered?
underscore[i] = guess; // replace it
if (underscore[i] == '_')
found = false;
}
if (found)
{
cout << "Good job!" << endl;
return 0;
}
//...