【发布时间】:2014-03-07 10:28:45
【问题描述】:
使用 C++,我正在尝试制作一个刽子手游戏,以便更好地使用 C++ 和一般编程。无论如何,我面临的问题是我不确定如何用用户猜到的字母替换字符串中的破折号。
我认为我的问题在于选择的单词是从数组中随机选择的,我不确定如何在包含猜测字符的随机选择的字符串中查找位置。
我已注释掉导致问题的区域。
#include <iostream>
#include <array>
#include <string>
#include <stdlib.h>
#include <time.h>
#include <cstddef>
#include <algorithm>
using namespace std;
int main()
{
string words[3] = {"stack", "visual", "windows"};
string guess;
cout << "Welcome to hangman.\n";
cout << "\n";
srand(time(NULL));
int RandIndex = rand() % 3;
string selected = words[RandIndex];
for (int i = 1; i <= selected.size(); i++) {
cout << "_ ";
}
cout << "\n";
cout << "\nType in a letter: ";
cin >> guess;
cout << "\n";
if (selected.find(guess) != string::npos) {
/*for (int i = 1; i <= selected.size(); i++) {
if (selected.find(guess) != string::npos) {
cout << "_ ";
} else {
cout << guess << " ";
}
}*/
} else {
cout << "\nNay!\n";
cout << "\n";
}
cout << "\n";
cout << "\n";
system("PAUSE");
return 0;
}
我正在考虑使用replace() 函数,但我在这里面临的问题是我没有替换selected 变量中的字符串,而是在对单词本身进行迭代,如果这有任何意义吗?
【问题讨论】:
-
我在大学的时候不得不做一个刽子手游戏。我将单词存储在一个字符串中,并在字符串中有一个不同字符的向量。显示单词中的每个字符时,检查它是否在向量中,如果是,则显示下划线。当用户猜测正确时,您从向量中删除字符。