存储txt文件值转换成二维数组

存储txt文件值转换成二维数组

问题描述:

首先,这里是我的code http://pastebin.com/BxpE7aFA

Firstly, here is my code http://pastebin.com/BxpE7aFA.

现在。我想读它看起来像这样 http://pastebin.com/d3PWqSTV 一个文本文件 并把所有这些整数到一个数组,称为水平。平的大小为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]?

检查矩阵初始的code,它应该是 INT级[高度] [宽度]; 不是 INT级[宽度] [高度]; 同时,你的数据行比宽度短。在code工作的下一个办法:通过电平矩阵的所有行循环,读取一行从一个文件中(文件>>行)指令,如果阅读是全成,然后我们填充行的水平矩阵,否则我们读到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;
    }