比较 char 和 char[i] 在刽子手游戏中不起作用
Compare char with char[i] not working in hangman game
我试图做一个刽子手游戏,我的想法是你给出字母和单词的数量,然后程序用 _
作为单词的字母填充一个字符。然后它会询问你一个字母,并比较该字母是否与给定单词中的任何字母匹配。然后它将相应的 _
替换为字母,但它不会替换它...
我做错了什么?
#include <iostream>
#include <conio.h>
#include <cstdlib>
using namespace std;
int main()
{
int game = 0;
int n = 0;
char blank[n - 1];
char palabra[n - 1];
char letra;
cout << "Input the number of letters of the word\n";
cin >> n;
cout << "Input the word\n";
cin >> palabra;
for (int i = 0; i < n; i++) {
blank[i] = '_';
}
while (game != 1) {
for (int i = 0; i < n; i++) {
if (letra == palabra[i]) {
blank[i] = letra;
}
else {
if (blank[i] != '_') {
blank[i] = blank[i];
}
else {
blank[i] = '_';
}
}
}
system("cls");
cout << "\n";
for (int i = 0; i < n; i++) {
cout << blank[i] << " ";
}
cout << "Input a letter" << endl;
cin >> letra;
}
getch();
return 0;
}
int n = 0;
char blank[n - 1];
这有三处错误:
n
初始化为0,但数组长度为0 - 1
。
直到用户输入 n
的值才真正知道,但您继续使用 n-1
条目声明了 blank
。
即使 n
被初始化为合理的东西,
的声明
char blank[n - 1];
不是合法的 C++ 语法。 C++ 中的数组的大小必须由编译时常量表示,而不是运行时变量。
要解决这些问题,请使用 std::string
而不是 char 数组。
如果这样做,代码将类似于:
#include <string>
#include <iostream>
int main()
{
int game = 0;
int n = 0;
std::string palabra;
char letra;
std::cout << "Input the number of letters of the word\n";
std::cin >> n;
std::cout << "Input the word\n";
std::cin >> palabra;
std::string blank(n, '_'); // create a string with n underscores
//...
}
其余代码应保持不变。程序的整体逻辑是否正确,那是另一个问题,但至少你没有字符数组的问题。
我试图做一个刽子手游戏,我的想法是你给出字母和单词的数量,然后程序用 _
作为单词的字母填充一个字符。然后它会询问你一个字母,并比较该字母是否与给定单词中的任何字母匹配。然后它将相应的 _
替换为字母,但它不会替换它...
我做错了什么?
#include <iostream>
#include <conio.h>
#include <cstdlib>
using namespace std;
int main()
{
int game = 0;
int n = 0;
char blank[n - 1];
char palabra[n - 1];
char letra;
cout << "Input the number of letters of the word\n";
cin >> n;
cout << "Input the word\n";
cin >> palabra;
for (int i = 0; i < n; i++) {
blank[i] = '_';
}
while (game != 1) {
for (int i = 0; i < n; i++) {
if (letra == palabra[i]) {
blank[i] = letra;
}
else {
if (blank[i] != '_') {
blank[i] = blank[i];
}
else {
blank[i] = '_';
}
}
}
system("cls");
cout << "\n";
for (int i = 0; i < n; i++) {
cout << blank[i] << " ";
}
cout << "Input a letter" << endl;
cin >> letra;
}
getch();
return 0;
}
int n = 0;
char blank[n - 1];
这有三处错误:
n
初始化为0,但数组长度为0 - 1
。直到用户输入
n
的值才真正知道,但您继续使用n-1
条目声明了blank
。即使
的声明n
被初始化为合理的东西,
char blank[n - 1];
不是合法的 C++ 语法。 C++ 中的数组的大小必须由编译时常量表示,而不是运行时变量。
要解决这些问题,请使用 std::string
而不是 char 数组。
如果这样做,代码将类似于:
#include <string>
#include <iostream>
int main()
{
int game = 0;
int n = 0;
std::string palabra;
char letra;
std::cout << "Input the number of letters of the word\n";
std::cin >> n;
std::cout << "Input the word\n";
std::cin >> palabra;
std::string blank(n, '_'); // create a string with n underscores
//...
}
其余代码应保持不变。程序的整体逻辑是否正确,那是另一个问题,但至少你没有字符数组的问题。