如何将文件读入数组以绘制游戏板C ++

问题描述 投票:0回答:1

我正在使用C ++构建Minesweeper游戏。现在,我迷失了尝试读取输入文件并使用内容构建游戏面板的样子,如下所示:GameBoard

这是我到目前为止所拥有的:

main.cpp

#include <iostream>
#include <string>

#include "UI.hpp"
#include "drawboard.hpp"

int main()
{

    UI start;
    start.Gameprompt();        

    int drawgame[4][4] = {{' ',' ',' ',' '},{' ',' ',' ',' '},{' ',' ',' ',' '},{' ',' ',' ',' '}};
    drawBoard(drawgame);


    return 0;
}

UI.hpp

#ifndef UI_HPP
#define UI_HPP


#include <iostream>
#include <fstream>
#include <string>

class UI
{

    private:
            std::string filename;


    public:
            void GamePrompt();


};


#endif

UI.cpp

#include <iostream>
#include <fstream>
#include <string>


#include "UI.hpp"


void UI::GamePrompt()
{
    std::ifstream inFS;

    while (!inFS.is_open())
    {
            std::cout << "Please enter a file name with the minefield information: " << std::endl;
            std::cin >> filename;
            inFS.open(filename.c_str());
    }


}

drawboard.hpp

#ifndef DRAWBOARD_HPP
#define DRAWBOARD_HPP

class drawBoard
{

    private:
            int board[4][4];

    public:
            drawBoard(int board[][4]);


};

#endif

drawboard.cpp

#include "drawboard.hpp"
#include<iostream>

drawBoard::drawBoard(int board[][4])
{

    std::cout << " 0 1 2 3 " << std::endl;
    for(int i = 0; i < 4; i++)
    {

            std::cout << " +---+---+---+---+" << std::endl;
            std::cout << i + 1;

            for(int j = 0; j < 4; j++)
            {

                    std::cout << " | " << board[i][j];

            }

            std::cout << " | " << std::endl;

    }

    std::cout << " +---+---+---+---+" << std::endl;

}

这些是我现在收到的错误:

main.cpp: In function ‘int main()’:
main.cpp:18:20: error: conflicting declaration ‘drawBoard drawgame’
drawBoard(drawgame);
                ^
main.cpp:16:6: error: ‘drawgame’ has a previous declaration as ‘int drawgame [4][4]’
int drawgame[4][4] = {{' ',' ',' ',' '},{' ',' ',' ',' '},{' ',' ',' ',' '},{' ',' ',' ',' '}};
  ^
main.cpp:16:6: warning: unused variable ‘drawgame’ [-Wunused-variable]

谢谢您的帮助

c++ data-structures minesweeper
1个回答
1
投票

此错误实际上有点晦涩...

当编译器看到行时

drawBoard(drawgame);

[它认为您正在将变量drawgame定义为drawBoard实例,即它认为您正在执行的操作]

drawBoard drawgame;

解决方案很简单,像平常一样定义变量,然后将数组传递给构造函数,如

drawBoard board(drawgame);

或如评论中所述,您可以做

drawBoard{drawgame};

但是这只会创建一个temporary drawBoard对象,该对象将立即被销毁。

© www.soinside.com 2019 - 2024. All rights reserved.