Module 7: Read the Grid from a File

This commit is contained in:
David Doblas Jiménez 2021-07-15 17:45:54 +02:00
parent c685a78b09
commit e5369e22bc
2 changed files with 42 additions and 28 deletions

54
a.c
View File

@ -2,42 +2,58 @@
#include <string> // support for strings
#include <vector> // support for vectors
#include <assert.h>
#include <fstream> // support for reading files
using namespace std;
// For compiling C++ code
// g++ a.c -o a
struct Grid
{
Grid(string n) {
Grid(string n)
{
name = n;
}
int rows() const { return lines.size(); }
int cols() const {
if (lines.empty()) {
int cols() const
{
if (lines.empty())
{
return 0;
} else {
return lines[0].size(); }
}
void Load() {
lines.push_back("DOG....");
lines.push_back("---....");
lines.push_back("----...");
lines.push_back("-------");
lines.push_back("...----");
lines.push_back("....---");
lines.push_back("....CAT");
else
{
return lines[0].size();
}
}
void Check() const {
void LoadFromFile(string filename)
{
ifstream f;
f.open("test");
while (!f.eof())
{
string line;
getline(f, line);
// cout << line << "\n";
if (!line.empty() && line[0] != '#')
{
lines.push_back(line);
}
}
}
void Check() const
{
for (string s : lines)
{
assert(s.size() == cols());
}
}
void Print() const {
void Print() const
{
cout << "Grid: " << name
<< " (rows=" << rows()
<< ", cols=" << cols() << ")\n";
for (string s : lines) {
<< " (rows=" << rows()
<< ", cols=" << cols() << ")\n";
for (string s : lines)
{
cout << " " << s << "\n";
}
}
@ -49,7 +65,7 @@ int main()
{
Grid grid("MY GRID");
grid.Load();
grid.LoadFromFile("test");
grid.Check();
grid.Print();
}

16
a.py
View File

@ -13,14 +13,12 @@ class Grid:
else:
return len(self.lines[0])
def Load(self):
self.lines.append("DOG....")
self.lines.append("---....")
self.lines.append("----...")
self.lines.append("-------")
self.lines.append("...----")
self.lines.append("....---")
self.lines.append("....CAT")
def LoadFromFile(self, filename):
with open(filename, 'r') as f:
for line in f:
#print(f"{line.rstrip()} ({len(line.rstrip())})")
if not line.startswith('#'):
self.lines.append(list(line.rstrip()))
def Check(self):
for s in self.lines:
@ -36,6 +34,6 @@ class Grid:
if __name__ == "__main__":
grid = Grid("MY GRID")
grid.Load()
grid.LoadFromFile("test")
grid.Check()
grid.Print()