【问题标题】:Compare char with char[i] not working in hangman game比较 char 和 char[i] 在hangman 游戏中不起作用
【发布时间】:2021-06-08 18:35:32
【问题描述】:

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

我做错了什么?

#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;字符空白[n -1];没有意义。问问自己这个数组有多少个元素?
  • 对动态大小的数组使用std::vector
  • @Pedro Juan 如果您的编译器支持可变长度数组并且 size_t 类型与 unsigned long long 类型具有相同的大小,则此声明 char blank[n - 1];声明一个包含 18446744073709551615 个元素的数组。:)
  • @Pedro Juan 还有这个变量 char letra;未初始化。因此,while 循环将在其第一次迭代中调用未定义的行为。
  • @Pedro Juan 您需要使用 std::string 类的对象而不是可变长度数组。

标签: c++ char


【解决方案1】:
int n = 0;
char blank[n - 1];

这有三个问题:

  1. n 初始化为 0,但随后数组将具有 0 - 1 长度。

  2. 直到用户输入n 的值才真正知道,但您继续声明blankn-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 
    //...
}

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-24
    • 1970-01-01
    相关资源
    最近更新 更多