验证 2D 字符数组的输入

Validating inputs for a 2D- Character Array

提问人:Adrian Pena 提问时间:10/25/2023 最后编辑:kiner_shahAdrian Pena 更新时间:10/25/2023 访问量:42

问:

我有一些代码正在处理,但我被卡住了。如何检查 2D 字符数组的字符输入是否正确?我正在模拟井字游戏,并且只需要“x”和“o”作为我的输入,其他任何内容都应该产生”cout << "Sorry you can only enter 'x' and 'o'" << endl; exit(1);"

这是我到目前为止尝试过的,但这不起作用!有人可以向我解释一下吗?我是 c++ 的初学者,所以我只知道基础知识,但基本上我必须检查所有 9 个数组位置是否有正确的输入或 .'x''o'

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

int main() {
    // Declare 2D array
    const int SIZE = 3;
    char board[SIZE][SIZE];

    // Read x's and o's
    cout << "Enter x's and o's on board (L-R, T-B): ";
    for (int r = 0; r < SIZE; r++)
        for (int c = 0; c < SIZE; c++)
            cin >> board[r][c];

    // Print 2D array
    cout << "\n+---+---+---+\n";
    for (int r = 0; r < SIZE; r++) {
        cout << "| ";
        for (int c = 0; c < SIZE; c++) 
            cout << board[r][c] << " | ";
        cout << "\n+---+---+---+\n";
    }

    // Check board contains only x's and o's
    bool valid = true;
    if (board[SIZE][SIZE] != 'x' || board[SIZE][SIZE] != 'o')
        valid = false;
    if (!valid) {
        cout << "Sorry, you can only enter x's and o's\n";
        exit(1);
    }

    // Check first diagonal to see who wins
    char winner = ' ';
    if ((board[0][0] == board[1][1]) && (board[1][1] == board[2][2]))
        winner = board[0][0];

    // Check second diagonal to see who wins
    if ((board[2][0] == board[1][1]) && (board[1][1] == board[0][2]))
        winner = board[0][0];

    // Check rows to see who wins
    for (int r = 0; r < SIZE; r++)
        if ((board[r][0] == board[r][1]) && (board[r][1] == board[r][2]))
            winner = board[r][0];

    // Check columns to see who wins
    for (int c = 0; c < SIZE; c++)
        if ((board[0][c] == board[1][c]) && (board[1][c] == board[2][c]))
            winner = board[c][0];
    // Print winner
    if (winner != ' ')
        cout << "Congratulations " << winner << " is the winner\n";
    else
        cout << "Sorry, no one wins\n";
    return 0;
}
C++ 数组 if-statement 布尔 井字棋

评论

1赞 Igor Tandetnik 10/25/2023
board[SIZE][SIZE] != 'x' || board[SIZE][SIZE] != 'o'始终是正确的。如果字符等于 ,则它显然不等于 ,反之亦然。你的意思是代替xo&&||
1赞 Igor Tandetnik 10/25/2023
此外,越界访问索引。有效索引通过 。您已经知道如何访问电路板的每个元素 - 您在上面,在打印出来的循环中进行。board[SIZE][SIZE]0SIZE-1
1赞 Adrian Pena 10/25/2023
谢谢你的解释!我的大脑现在被期中考试炸了,但哇,这是一个简单的解决方法!它现在起作用了!
0赞 paddy 10/25/2023
注意缩进。以一致性为目标。它将帮助您(和其他人)阅读您的代码。
0赞 PaulMcKenzie 10/25/2023
@AdrianPena 我现在脑子里被期中考试炸了——你可以创建一个函数,叫它。然后在您的函数中,只需调用即可确定该字符是否无效。bool isValidEntry(char c) { return c == 'x' || c == 'o'; }mainif (!isValidEntry(board[r][c]))

答: 暂无答案