简体   繁体   中英

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

So I'm trying to create a snake game in 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. 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';
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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