![](/img/trans.png)
[英]How to check if the any SYMBOL exists in the string except '-','_','.', '@' in C++?
[英]How to add any symbol instead another symbol in string C++?
我正在編寫一個“Hangman”游戲控制台應用程序,我想在字符串中添加一個符號而不是另一個符號。
我嘗試了擦除,刪除和替換功能,但是它對我不起作用。 因為我在const char *中有一個符號,所以無法將其轉換為char。
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <vector>
#include <algorithm>
#include <string.h>
using namespace std;
string conceivedword;
string hint;
string choice;
string first_player_word;
string characterstring;
int counter = 0;
void first_player() {
cout << "Welcome to Hangman! //Firstgamerzone " << endl;
cout << "Please conceive the word" << endl;
getline(cin, conceivedword);
cout << "Type the hint" << endl;
getline(cin, hint);
system("cls");
cout << " The hint is: " << hint << endl;
}
void second_player() {
while (0 == 0) {
cout << "Are you inputting word or character?" << endl;
//while (0 == 0) {
getline(cin, choice);
if (choice == "word" || choice == "sitkva" || choice == "sityva") {
cin >> first_player_word;
if (first_player_word == conceivedword) {
cout << "Congrats! You're winner! shen moige gazqura :D " << endl;
break;
}
else {
counter += 1;
if (counter > 5) {
cout << "Bad luck. You lost. You had only 5 attempts." << endl;
break;
}
cout << "Bad luck. Try again" << endl;
//second_player();
}
}
else if (choice == "character" || choice == "aso") {
cin >> characterstring;
if (characterstring.length() > 1) cout << "Hey,Your Lier! You lost." << endl;
else {
counter += 1;
const char *character = characterstring.c_str();
int exists = conceivedword.find(character);
//cout << exists << endl;
int index = conceivedword.find(character);
if (exists > 0) {
if (counter > 5) {
cout << "You lost. You had only 5 attempts" << endl;
break;
}
cout << "Right. You rock: " << endl;
int length = conceivedword.length();
for (int i = 0; i < conceivedword.length(); i++) {
if (i == index) {
cout << character;
//replace(conceivedword.begin(), conceivedword.end(), '_', character);
}
//cout << conceivedword.length() << endl;
//if (i == index) {
//replace(conceivedword.begin(), conceivedword.end(), '_', '*');
//}
cout << "_" << " ";
//cout << endl;
}
second_player();
cout << endl;
}
if(exists <= 0) {
cout << "Not right. Try again" << endl;
second_player();
}
}
break;
}
}
}
int main() {
system("Color 3");
first_player();
second_player();
system("pause");
return 0;
}
到目前為止,替換功能不起作用。
您不能替換字符串中的字符。 您應該做的是將std :: string用作std :: vector <char>(因為它確實很相似)。
您可以將字母分配給單詞中的某個位置:
word [2] = yourLetter;
您甚至不需要知道以前的位置,因此您無需替換它-分配更加容易。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.