使用 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
变量中的字符串,而是通过迭代这个词本身,是否有任何意义?
最佳答案
使用第二个字符串,用下划线初始化。如果 find
函数没有返回string::npos
,它会返回字符串中的位置,而这与您应该更改的位置相同在带有下划线的字符串中也是如此。
关于C++ - 用字符替换 "_",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22247554/