将txt文件值存储到2D数组中 [英] Store txt file values into 2D array

查看:153
本文介绍了将txt文件值存储到2D数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,这是我的代码 http://pastebin.com/BxpE7aFA

现在。我想读取一个类似于 http://pastebin.com/d3PWqSTV
的文本文件,将所有这些整数放入一个数组,称为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.

我唯一的问题是,你看到???。如何从文件中获取字符,并将其放入级别[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]; int level [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文件值存储到2D数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆