简体   繁体   English

C ++读取文本文件以填充2D数组

[英]C++ Read a text file to populate a 2D array

So I'm trying to create a snake game in C++. 所以我试图用C ++创建一个蛇游戏。 The player is going to have a choice of levels when they start the game of varying difficulties. 玩家在开始各种难度的游戏时将选择等级。 Each level is stored in a .txt file and I'm having issues populating the array from the file. 每个级别都存储在一个.txt文件中,我在从文件填充数组时遇到了问题。 Here's the code I have so far with regards to getting the array from the file. 这是到目前为止我从文件中获取数组的代码。

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

int main()
{
    ifstream fin("LevelEasy.txt");
    fin >> noskipws;

    char initialLevel[10][12];

    for (int row = 0; row < 10; row++)
    {
        for (int col = 0; col < 12; col++)
        {
            fin >> initialLevel[row][col];
            cout << initialLevel[row][col];
        }
        cout << "\n";
    }

    system("pause");

    return 0;
}

It populates the first line and prints it perfectly fine. 它填充第一行并完美打印。 The issue arises when it gets to the end of the line, which subsequently causes problems on every line afterwards. 当到达行尾时会出现问题,此后随后会在每行上引起问题。 I expect it to print like so; 我希望它能像这样打印;

############
#          #
#          #
#          #
#          #
#          #
#          #
#          #
#          #
############

But it just ends up printing something like this; 但这最终只会打印出这样的内容;

############

#
#
#
 #
#
  #
#
   #
#
    #
#
     #
#
      #
#
       #
###

I'm just wondering how upon reaching the end of the line, I can stop adding to the line of the array and move to the next instead? 我只是想知道如何到达行尾时,我可以停止添加到数组的行,而是移到下一行? Any help would be appreciated. 任何帮助,将不胜感激。

Here's what I would use to do that: 这是我用来做的事情:

#include <iostream>
#include <fstream>
#include <string>
#include <vector>

int main() {
    std::ifstream fin("LevelEasy.txt");

    std::vector <std::string> initialLevel;
    std::string line;

    while(std::getline(fin,line)) {
        initialLevel.push_back(line);
        std::cout << line << '\n';
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM