将 txt 文件值存储到二维数组中 [英] Store txt file values into 2D array
问题描述
首先,这是我的代码http://pastebin.com/BxpE7aFA.
现在.我想阅读一个看起来像这样的文本文件 http://pastebin.com/d3PWqSTV并将所有这些整数放入一个名为 level 的数组中.level 的大小为 100x25,在顶部声明.
Now. I want to read a text file which looks like this http://pastebin.com/d3PWqSTV and put all those integers into an array, called level. level has a size of 100x25, which is declared at the top.
我现在唯一的问题是你在哪里看到???.如何从文件中获取字符,并将其放入 level[i][j]?
My only problem now is where you see the ???. How do I get the char from the file, and put that into level[i][j]?
推荐答案
检查矩阵初始化的代码,应该是int level[HEIGHT][WIDTH];
不是intlevel[WIDTH][HEIGHT];
还有,你的数据行比 WIDTH
短.代码的工作方式如下:我们遍历一个级别矩阵的所有行,通过 (file >> row)
指令从文件中读取一行,如果读取成功,那么我们填充行在一个级别矩阵中,否则我们会读取 EOF 从而中断循环.
Check the code of initialization of a matrix, it should be int level[HEIGHT][WIDTH];
not int level[WIDTH][HEIGHT];
also, your data rows are shorter than WIDTH
. The code works the next way: we loop through all lines of a level matrix, read a row from a file by (file >> row)
instruction, if read was successfull, then we populate row in a level matrix, otherwise we read EOF so break from loop.
#include<iostream>
#include<fstream>
#include<string>
#include <limits>
static const int WIDTH = 100;
static const int HEIGHT = 25;
int main()
{
int level[HEIGHT][WIDTH];
for(int i = 0; i < HEIGHT; i++)
{
for(int j = 0; j < WIDTH; j++)
{
level[i][j] = 0;
}
}
std::ifstream file("Load/Level.txt");
for(int i = 0; i < HEIGHT; i++)
{
std::string row;
if (file >> row) {
for (int j = 0; j != std::min<int>(WIDTH, row.length()) ; ++j)
{
level[i][j] = row[j]-0x30;
}
std::cout << row << std::endl;
} else break;
}
return 0;
}
这篇关于将 txt 文件值存储到二维数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!