Store txt file values into 2D array

﹥>﹥吖頭↗ 提交于 2019-12-19 05:01:20

问题


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

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.

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]?


回答1:


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;
    }



回答2:


You can use file >> level[i][j]; to populate your 2D char array level[ ][ ] with the contents of level.txt.

#include<iostream>
#include<fstream>
#include<string>
using namespace std;

static const int WIDTH = 100;
static const int HEIGHT = 25;
char level[HEIGHT][WIDTH]={0};


int main()
{

    std::ifstream file;
    file.open("level.txt");

    if(file.is_open())
    {
            std::cout << "File Opened successfully!!!. Reading data from file into array" << std::endl;
            while(!file.eof())
            {
                    for(int i = 0; i < HEIGHT; i++)
                    {
                            for(int j = 0; j < WIDTH; j++)
                            {
                                    //level[i][j] = ???
                                    file >> level[i][j];
                                    std::cout << level[i][j];
                            }
                            std::cout << std::endl;
                    }
            }

    }
    file.close();

    return 0;
}


来源:https://stackoverflow.com/questions/30441732/store-txt-file-values-into-2d-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!