C++比较字符串数组元素

标签 c++ arrays

<分区>

我是 C++ 的新手,因为我的第一个任务是制作黑白棋游戏,但在更换棋子时遇到了问题。我试图比较字符串元素,但没有任何反应。这是向您展示问题所在的代码。

#include <iostream>
#include <string>
using namespace std;
void displayTop();



int main() {
    string board [8][8] = {

        " "," "," "," "," "," "," "," ",
        " "," "," "," "," "," "," "," ",
        " "," "," "," "," "," "," "," ",
        " "," "," ","W","B"," "," "," ",
        " "," "," ","B","W"," "," "," ",
        " "," "," "," "," "," "," "," ",
        " "," "," "," "," "," "," "," ",
        " "," "," "," "," "," "," "," ",

    };
    displayTop();
    cout << endl;

    for (int row = 0; row < 8; row++){
        cout << "   ";

        for (int column = 0; column < 8; column++){
            cout << board[row][column] << "    ";
        }
        cout << endl;
        displayTop();
        cout << endl << endl;
    }
    if(board[0][0] == " "){
        board[0][1] = "W";
    }
}
void displayTop(){
    for (int i = 0; i < 8; i++){
        cout << "+----";
    }
    cout << endl;

}

最佳答案

您的比较是在显示板后进行的,这可能是您没有看到任何变化的原因。

为什么不使用 char 而不是 string 呢?

    #include <iostream>
    using namespace std;
    void displayTop();

    int main() {
        char board [8][8] = {

            ' ',' ',' ',' ',' ',' ',' ',' ',
            ' ',' ',' ',' ',' ',' ',' ',' ',
            ' ',' ',' ',' ',' ',' ',' ',' ',
            ' ',' ',' ','W','B',' ',' ',' ',
            ' ',' ',' ','B','W',' ',' ',' ',
            ' ',' ',' ',' ',' ',' ',' ',' ',
            ' ',' ',' ',' ',' ',' ',' ',' ',
            ' ',' ',' ',' ',' ',' ',' ',' ',

        };

        if(board[0][0] == ' '){
            board[0][1] = 'W';
        }

        displayTop();
        cout << endl;

            for (int row = 0; row < 8; row++){
                cout << "   ";

            for (int column = 0; column < 8; column++){
                cout << board[row][column] << "    ";
            }
            cout << endl;
            displayTop();
            cout << endl << endl;
        }
    }

    void displayTop(){
        for (int i = 0; i < 8; i++){
            cout << "+----";
        }
        cout << endl;
    }

关于C++比较字符串数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31580741/

相关文章:

javascript - 无法替换字符串的特定部分

c++ - "ODR-use"是什么意思?

javascript - 将元素添加到 javascript "dictionary"数组中

c++ - C++中的char数组赋值

javascript - 在 Javascript 中如何检查提供的参数是否是字节数组类型?

c++ - 当两个父类(super class)具有同名但签名不同的成员函数时不明确

c++ "Run-Time Check Failure #2 - Stack around the variable ' board' 已损坏”

c++ - QSerialPort::readLine 在 MS Windows 上无法正常工作

java - 寻找最大乘积的算法方法

c - 测试用例中的段错误