难以比较两个阵列

时间:2014-02-19 23:12:25

标签: c++ arrays

#include<iostream>
#include <ctime>
#include <cstdlib>
using namespace std;

int main()
{
char wordOne[5][9] = { {"elephant"},
                       {"imperial"},
                       {"absolute"},
                       {"absinthe"},
                       {"computer"} };

char hangman[9] = {"********"};

char guess;

int r;
srand( time(0));
r = rand()%5;
wordOne[r];

cout << "Guess the secret eight letter word before you run out of guesses! Go: " << endl;

for (int x = 0; x < 8; ++x)

cout << hangman[x] << endl;
cin >> guess;

while (hangman[0] == '*' || hangman[1] == '*' || hangman[2] == '*' || hangman[3] == '*' || hangman[4] == '*' || hangman[5] == '*' || hangman[6] == '*' || hangman[7] == '*')

{
cout << "Guess the secret eight letter word before you run out of guesses! Go: ";
for(int x = 0; x < 8; ++x)
        cout << hangman[x];
        cout << endl;
        cin >> guess;

    for(int x = 0; x < 8; ++x)
    {
        if (wordOne[hangman[x]][x] == guess)
            {
                hangman[x] = guess;
            }
    }

for(int x = 0; x < 8; ++x)
    cout << hangman[x] << endl;
}

system("PAUSE");
return 0;
}

对于一个项目,我们被要求创建一个只显示星号的一维数组。然后,使用二维数组,存储5个不同的8个字母单词。该程序应该随机选择一个,然后用户输入试图猜测该单词的随机字母。它基本上复制了刽子手。在猜到字母时,星号应该用正确的字母代替。例如,如果单词是elephant并且e首先被猜到,那么程序将显示e ***等等。我已经得到了编译程序,但我无法弄清楚如何更改代码以便替换星号并且程序正常运行。任何反馈都会非常感激。

2 个答案:

答案 0 :(得分:3)

wordOne[hangman[x]][x]让我们说x = 1这会将代码等同于wordOne['*'][1]。不应该是wordOne[r][x] == guess吗?我添加了一个int来跟踪猜测量,并在while循环中添加了一个检查,以查看用户是否猜到了最大次数。

#include<iostream>
#include <ctime>
#include <cstdlib>
using namespace std;

int main()
{
    char wordOne[5][9] = { {"elephant"},
    {"imperial"},
    {"absolute"},
    {"absinthe"},
    {"computer"} };

    char hangman[9] = {"********"};

    char guess;

    int r;
    srand( time(0));
    r = rand()%5;
    wordOne[r];
    int numGuesses = 10;

    cout << "Guess the secret eight letter word before you run out of guesses! Go: " << endl;

    for (int x = 0; x < 8; ++x)
        {
        cout << hangman[x] << endl;
    }
    while (numGuesses > 0 && (hangman[0] == '*' || hangman[1] == '*' || hangman[2] == '*' || hangman[3] == '*' || hangman[4] == '*' || hangman[5] == '*' || hangman[6] == '*' || hangman[7] == '*'))

    {
        cout << "Guess the secret eight letter word before you run out of guesses! Go: ";


        for(int x = 0; x < 8; ++x)
        {
            cout << hangman[x];
        }

        cout << endl;

        cin >> guess;
        --numGuesses;

        for(int x = 0; x < 8; ++x)
         {
            if (wordOne[r][x] == guess)
            {
                hangman[x] = guess;
            }
        }

        for(int x = 0; x < 8; ++x)
        {
            cout << hangman[x] << endl;
        }
    }

    system("PAUSE");
    return 0;
}

答案 1 :(得分:2)

wordOne[hangman[x]][x]更改为wordOne[r][x]。 另外,我建议不要在for循环中打印endl,因为它会在不同的行上打印每个字符。