c++ - 读入单词搜索游戏 C++ 的文件

标签 c++ vector fstream ifstream

我正在尝试读取一个文件并创建一个 2D vector 来存储单词搜索游戏的游戏板,但我似乎无法让它读取超过第一行的内容。我确定它很小,但我为“board” vector 放置了一个测试显示,显示的只是文本文件的第一行。

这是我的一些代码:

'董事会.cpp'

#include "stdafx.h"
#include "Board.h"
#include <fstream>
#include <iostream>
using namespace std;


Board::Board(void)
: rows(0)
{
}


Board::~Board(void)
{
}

void Board::readInFile(void)
{
    ifstream indata;
    indata.open("Puzzle.txt");
    indata >> rows;
    for(int i = 0; i < rows; i++){
        char tmpChar;
        for(int j = 0; j < rows; j++){
            indata >> tmpChar;
            row.push_back(tmpChar);
        }
        board.push_back(row);
    }
    indata.close();
}

'董事会.h'

#pragma once
#include <vector>
using namespace std;
class Board
{
public:
    Board(void);
    ~Board(void);
    void readInFile(void);
protected:
    vector<vector<char>> board;
    vector<char>row;    
protected:
    int rows;
};

下面是文本文件的设置方式:

16

BDXWASEESPHWEBGB

SIGJVAWDFLCTZIAM

恩克维斯马纳埃布里

IKOEOPZLUKMVJDDL

KLIRELOBSNPOFWEC

SBOHKLLRHSIFPANA

RSKWMEEEPEITPTPE

EZPIELLLYMOOQCDH

团结一致

ASIOJNFOPKAJAPBP

WLRCIILROZXLSCID

滑板GCLCIA

LLABESABIVOTNVVE

VOFRISBEETMIEVZG

BWADEVAUCYCSWING

XNJFJPZHBTBFTSAW

最佳答案

有很多更好的方法来处理输入文件。首先,而不是使用 vector<char> , 只需使用 std::string ,而不是使用 vector<vector<char> > , 只需使用 vector<string> .我不确定我明白为什么 row如果它仅用于填充 board,则它是该类的成员.任何时候你需要板上的最后一项,你可以做 board.back()*board.rbegin() .

void Board::readInFile(void)
{
    ifstream indata("Puzzle.txt", ios::in);
    if(!ifstream.is_open())
        return;
    indata >> rows;    //you don't really need to do this if you take 
                         //the row count out of the file, but if you can't 
                         //change the file, leave it in so as not to corrupt 
                         //the loop that follows
    string line;
    while(getline(indata, line)){
        board.push_back(line);
    }
    indata.close();
}

真的,您不需要让文件存储 rows变量。


如果 readInFile 将文件名作为参数,那么您的函数也将更具可重用性,这样它就可以打开任何文件,而不仅仅是一个特定的文件名。

关于c++ - 读入单词搜索游戏 C++ 的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20478749/

相关文章:

数组中struct中的c++成员函数指针给出编译错误

c++ - 将元素从 char vector 复制到字符串 vector

C++ vector 初始化

c++ - 在 C++ 中删除 ofstream 中的一行

c++ - vector::clear:内存问题

c++ - 当我们可以更有效地使用 vector 来实现优先级队列时,为什么要使用堆来实现它

C++:读取没有扩展名的文件

c++ - 如何知道指定的文件是否被正确读取?

c++ - 将二进制编码的无符号字符转换为整数

r - 基于另一个向量的条件向量创建