我想在C++(11)中做一个简单的猜字游戏,因为它需要一个"hidden word"
显示给玩家我已经做了两个字符串;第一个可见的"test"
,另一个只填充下划线"____"
。我用string::iterator
做了一个循环,将字符串中的每个字符与用户输入的给定(char
)输入进行比较。C++ <algorithm>替换所有发生的不工作
这里的问题是,它并没有在字符串中代替人OCCURENCES的第一次我给这将导致“t__t
”的“t
”的输入,而不是“t___
”
为过程我使用的从<algorithm>
头 看起来像这样的replace
功能:
replace(str.begin(), str.end(), str.at(char_idx), newLetter);
和这个函数是福尔循环内它迭代槽字符串;在另一个叫功能可按checkLetter()
void checkLetter(char &newLetter, string &randstr, int &strlen, string &hiddenWord){
string::iterator it;
char char_idx;
for(auto it = randstr.begin(); it != randstr.end();++it){
if(*it == newLetter){
char_idx=randstr.find(*it);
replace(hiddenWord.begin(), hiddenWord.end(), hiddenWord.at(char_idx), newLetter);
}
}
cout << hiddenWord << endl;
}
现在这是输出的样子:
The Word is 4 letters long.
t
t___
e
te__
s
tes_
t
tes_
,但是当我跑的是如
string RandomWord = "test";
replace(RandomWord.begin(),RandomWord.end(),'t','S');
cout << RandomWord << endl;
一个简单的版本,它提供了'SesS'
全部代码:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
// Function Declaration
string getRandWord();
void checkLetter(char&, string&, int&, string&);
int main() {
// string RandomWord = getRandWord();
string RandomWord = "test";
string hiddenWord = "";
unsigned long int _length_ = RandomWord.length();
int chances = int(_length_)+1;
char newLetter;
hiddenWord.append((_length_),'_');
cout << "The Word is "<< _length_ <<" letters long." << endl;
while(chances > 0){
cin >> newLetter;
checkLetter(newLetter, RandomWord, chances, hiddenWord);
chances--;
}
return 0;
}
// Functions
void checkLetter(char &newLetter, string &randstr, int &strlen, string &hiddenWord){
string::iterator it;
char char_idx;
for(auto it = randstr.begin(); it != randstr.end();++it){
if(*it == newLetter){
char_idx=randstr.find(*it);
replace(hiddenWord.begin(), hiddenWord.end(), hiddenWord.at(char_idx), newLetter);
}
}
cout << hiddenWord << endl;
}
string getRandWord(){
string filePath = "/Users/nedimkanat/XCODE/testcpp/testcpp/";
enum sizes {
ARRAY_SIZE = 5
};
// set seed
srand((unsigned)time(0));
// get random int between 0 and 5
int randint = rand() % ARRAY_SIZE;
// str to store each line from file
string str;
// array to store 5 (random) words
vector<string> arr;
// initialize file object & open file
ifstream file(filePath+"words.txt");
int counter = 0;
// loop trough file
if (file.is_open()){
while (getline(file,str) && counter < ARRAY_SIZE){
arr.push_back(str);
counter++;
}
file.close();
} else {
cout << "File is not open" << endl;
}
// send away random word
if(arr.empty()){
cout << "CANCER" << endl;
}
return arr.at(randint);
}
非常感谢大家:) –