当前我正在研究一个hang子手游戏,我之前编码它只能用于5个字母的单词,但现在想要处理任何长度的单词,我怎么能改变这个代码,使其工作如何我想要它?在Hang子手游戏中检查任意大小的字母
#include "stdafx.h"
#include <iostream>
#include <string>
#include <stdlib.h>
#include <cstdlib>
using namespace std;
int main()
{
string word;
int tries;
string guess;
string wordguess;
string output;
cout << "Enter a word for player two to guess: ";
cin >> word;
system("CLS");
cout.flush();
cout << "Guess the word!" << endl;
for (int i = 0; i < word.length(); i++)
{
cout << "_ ";
}
cout << "Enter a letter: ";
cin >> guess;
for (int tries = 5; tries > 0; tries--)
{
if (guess[0] == word[0]) {
output[0] = word[0];
cout << "You guessed the first letter! Good job!" << endl;
}
if (guess[0] == word[1]) {
output[2] = word[1];
cout << "You guessed the second letter! Good job!" << endl;
}
if (guess[0] == word[2]) {
output[4] = word[2];
cout << "You guessed the third letter! Good job!" << endl;
}
if (guess[0] == word[3]) {
output[6] = word[3];
cout << "You guessed the fourth letter! Good job!" << endl;
}
if (guess[0] == word[4]) {
output[8] = word[4];
cout << "You guessed the fifth letter! Good job!" << endl;
}
cout << output << endl;
cout << "You have " << tries << " tries left. Take a guess at the word: " << endl;
cin >> wordguess;
if (wordguess == word)
{
cout << "Congratulations, you guessed the word correctly!" << endl;
break;
}
}
system("pause");
return 0;
}
正如你可以告诉我检查从0到4(第一到第五个字母)的每个位置。我知道有很多方法可以让我更好地编码,但正如你所猜测的,我是编码新手,这是我想到的方式。请注意,这仍然是一项正在进行的工作,因此尚未完全完成。任何帮助将是伟大的!
我认为你正在寻找一个字母'的std :: set'那就是这个词。 –
听起来像它会起作用,所以如果这个词是“玩”,它会认为它是一组p,l,a和y? – zhodges10
'output [x]'是未定义的行为,因为'output'是空的(它不会自动增长字符串)。你可以在'word'中的字符上使用循环,但是你需要一些通用的方法来获得英文单词“first”,“second”等。 – aschepler