我正在尝试读取一个文件并创建一个 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/