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

时间:2015-07-23 07:25:59

标签: 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;

}

1 个答案:

答案 0 :(得分:0)

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

为什么不使用char代替字符串?

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