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

问题描述 投票:0回答:1

所以我试图用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;
}

它填充第一行并完美打印。当它到达生产线末端时会出现问题,随后在每条生产线上都会出现问题。我希望它能像这样印刷;

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

但它最终会打印出这样的东西;

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

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

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

c++
1个回答
3
投票

这是我用来做的事情:

#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';
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.