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

C++ Read a text file to populate a 2D array

本文关键字:填充 2D 数组 文件 读取 取文本 C++      更新时间:2023-10-16

所以我正在尝试在C++创建一个贪吃蛇游戏。玩家在开始不同难度的游戏时可以选择关卡。每个级别都存储在一个.txt文件中,我在从文件中填充数组时遇到问题。这是我到目前为止关于从文件中获取数组的代码。

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

它填充第一行并完美打印。当它到达行尾时会出现问题,随后会导致之后每行出现问题。我希望它像这样打印;

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

但它最终只是打印了这样的东西;

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

只是想知道在到达行尾后,我如何停止添加到数组的行并移动到下一个?任何帮助将不胜感激。

以下是我用来执行此操作的方法:

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