[英]Code doesn't work and I don't know why. Making Hangman game
I'm new to C++ and coding.我是 C++ 和编码的新手。 I tried to make a hangman game as a beginner project.
我尝试将刽子手游戏作为初学者项目。 The problem I have is that the game only works when the letters of the word is typed in order.
我的问题是游戏只在按顺序输入单词的字母时才有效。 If the word is "flow" for instance, I have to type each letter consecutively (f,l,o,w).
例如,如果单词是“flow”,我必须连续输入每个字母 (f,l,o,w)。 Any other variations is not accepted and I don't know why.
不接受任何其他变化,我不知道为什么。 I need help debugging this issue.
我需要帮助调试这个问题。 I'm not sure if
.replace
is the method I should be using here.我不确定
.replace
是否是我应该在这里使用的方法。 I found this method on the internet and I thought it would do what I needed it to do.我在互联网上找到了这种方法,我认为它可以做我需要做的事情。
#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;
}
Here are some observations that might help you:以下是一些可能对您有所帮助的观察结果:
Don't declare all variables at the top of your function.不要在函数顶部声明所有变量。 Declare them as you need them .
在需要时声明它们。
Avoid hard-coding ( wordList[5]
).避免硬编码(
wordList[5]
)。 Add as many as strings as you need in your array.在数组中添加任意数量的字符串。 Use the following to find out how many are (see sizeof ):
使用以下内容找出有多少(请参阅sizeof ):
string wordList[] = { "closet", "flow", "sheep", "see", "chocolate" }; size_t wordCount = sizeof wordList / sizeof wordList[0];
You do not need to manually fill the underscore
string.您不需要手动填充
underscore
字符串。 Use the following constructor:使用以下构造函数:
string underscore(word.length(), '_');
The user might enter uppercase letters .用户可能会输入大写字母。 Convert them to lowercase.
将它们转换为小写。 Otherwise you will not find them:
否则你不会找到它们:
guess = tolower(guess);
You do not need fancy functions to find out where the entered character is located.您不需要花哨的函数来找出输入的字符所在的位置。 Just use a loop :
只需使用循环:
//... 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; } //...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.