比较 char 与 char[i] 在刽子手游戏中不起作用

问题描述

我试图做一个刽子手游戏,我的想法是你给出字母和单词的数量,然后程序用 _ 作为单词的字母填充一个字符。然后它会问你一个字母,并比较该字母是否与给定单词中的任何字母匹配。然后它用字母替换相应的 _,但它不替换它...

我做错了什么?

#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];

这有三个问题:

  1. n 被初始化为 0,但随后数组的长度为 0 - 1

  2. n 的值在用户输入之前是未知的,但您继续使用 blank 条目声明了 n-1

  3. 即使 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 
    //...
}

其余的代码应该保持不变。程序的整体逻辑是否正确,那就是另一个问题了,但至少你没有字符数组的问题。