From e5369e22bce22950c9dfcaf8a5416dba471e5e1d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?David=20Doblas=20Jim=C3=A9nez?= Date: Thu, 15 Jul 2021 17:45:54 +0200 Subject: [PATCH] Module 7: Read the Grid from a File --- a.c | 54 +++++++++++++++++++++++++++++++++++------------------- a.py | 16 +++++++--------- 2 files changed, 42 insertions(+), 28 deletions(-) diff --git a/a.c b/a.c index 79d48ab..157b6d0 100644 --- a/a.c +++ b/a.c @@ -2,42 +2,58 @@ #include // support for strings #include // support for vectors #include +#include // 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(); } \ No newline at end of file diff --git a/a.py b/a.py index d37a58f..572a233 100644 --- a/a.py +++ b/a.py @@ -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() \ No newline at end of file