C++ Hangman 交换实际字符的下划线

标签 c++ string char

我正在用 C++ 为 Uni 评估开发 Hangman 游戏,但在用户键入字母后我无法显示隐藏的单词。所以我得到的单词显示为“_ _ _ _ _ _ _”,但是当我键入一个字母时,它不会将下划线替换为实际字母。

game::game() {

words[0] = "strongly";
words[1] = "cheese";
words[2] = "computer";
words[3] = "coffee";
words[4] = "potatoes";         //words that can be in the game
words[5] = "zebra";
words[6] = "extinguisher";
words[7] = "solution";
words[8] = "diligent";
words[9] = "flabbergasted";

numGuesses = 0;

hiddenWord = words[rand() % 10]; //pick a random word from array words

completedWord = hiddenWord;

//for loop for changing the word to underscores
for (int i = 0; i < completedWord.length(); i++) {
    completedWord[i] = '_';

}   

//for loop adding a space after underscore
for (int i = 0; i < completedWord.length(); i++) {
    cout << completedWord[i] << " ";


}

cout << endl;
cout << "Please enter a letter: ";


char guessedLetter;
cin >> guessedLetter;

if (guessedLetter = completedWord[0]) {
    completedWord = guessedLetter;
    //cout << guessedLetter << endl;
    cout << completedWord << endl;


} 

}

我的整个程序分为不同的头文件和cpp 文件。所以上面的代码来 self 的 gameguesses.cpp,它的标题如下:

    class game {
public:
    string words[10];
    game();
    string hiddenWord;
    int numGuesses;

    string completedWord;

};

这就是我实际得到的: My code problem

将不胜感激。谢谢!

最佳答案

我看到 2 个问题:

if (guessedLetter = completedWord[0])

该行需要 == 而不是 =。

其次,您仅将猜测与隐藏单词的第一个字母进行比较。您需要编写一个循环来检查每个字母并在匹配猜测的位置进行替换,而不仅仅是在元素 [0] 中。

关于C++ Hangman 交换实际字符的下划线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32751928/

相关文章:

编译错误,成员不是 union 体的成员 |使用指针/结构

C++ LPCTSTR 到 char*

java - 如何从InputStreamReader读取整数

c++ - 如何编写垂直右侧的 IE 资源管理器栏

c++ - 通过 shared_ptr 返回的 Singleton 对象是线程安全的吗?

android - 如何在 android strings.xml 中写入字符 &

java - 了解removeChar方法

c++ - 编码(marshal) C++ 锯齿状数组给出 "Invalid managed/unmanaged type combination"错误

c++ - 使用 Log4cxx 记录到 Windows 事件

java - StringIndexOutOfBoundsException 不清楚