Reputation: 83
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.
Upvotes: 0
Views: 443
Reputation: 1
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';
}
}
Upvotes: 3