From 14e8d8112f0db9575838b40355197b9fc196a6ba Mon Sep 17 00:00:00 2001 From: Loek Le Blansch Date: Thu, 13 Jun 2024 11:13:48 +0200 Subject: read filename from argv or contents from stdin --- Parser.cpp | 4 ++++ Parser.h | 1 + docs/class-diag.puml | 2 ++ main.cpp | 30 ++++++++++++++++++++---------- 4 files changed, 27 insertions(+), 10 deletions(-) diff --git a/Parser.cpp b/Parser.cpp index 08ff2b0..9b98267 100644 --- a/Parser.cpp +++ b/Parser.cpp @@ -83,3 +83,7 @@ void Parser::parse(string input) { parse(s); } +Parser::Parser(Circuit & circuit) { + set_circuit(circuit); +} + diff --git a/Parser.h b/Parser.h index b6d7bd5..271d0f4 100644 --- a/Parser.h +++ b/Parser.h @@ -15,6 +15,7 @@ using std::string; class Parser { public: Parser() = default; + Parser(Circuit & circuit); virtual ~Parser() = default; void parse(string input); diff --git a/docs/class-diag.puml b/docs/class-diag.puml index 0417c49..b32b9bf 100644 --- a/docs/class-diag.puml +++ b/docs/class-diag.puml @@ -6,6 +6,7 @@ skinparam classAttributeIconSize 0 class main { +main(int argc, char** argv) : int + +open_input(int argc, char** argv) : istream* } hide main circle @@ -169,6 +170,7 @@ exception ParserException { class Parser { +Parser() + +Parser(Circuit& circuit) +~Parser() -circuit : Circuit* -operator<<(Parser& parser, istream s) : istream& diff --git a/main.cpp b/main.cpp index fd528f5..d8720c1 100644 --- a/main.cpp +++ b/main.cpp @@ -1,5 +1,6 @@ #include #include +#include #include "Parser.h" #include "Circuit.h" @@ -9,19 +10,30 @@ using std::cout; using std::endl; using std::ifstream; +using std::istream; -int main(int argc, char** argv) { - Parser main_parser; - Circuit circuit; +istream * open_input(int argc, char** argv) { + if (argc > 1) { + ifstream * file = new ifstream(argv[1]); + if (!file->is_open()) return nullptr; + return file; + } + + return &std::cin; +} - main_parser.set_circuit(circuit); +int main(int argc, char** argv) { + istream * input = open_input(argc, argv); + if (input == nullptr) { + cout << "Could not open file" << endl; + return EXIT_FAILURE; + } - // ifstream file("circuits/and-test.txt"); - ifstream file("circuits/full-adder.txt"); + Circuit circuit; + Parser parser(circuit); try { - file >> main_parser; - // main_parser << file; + *input >> parser; } catch (ParserException & e) { cout << "Parser error: " << e.what() << endl; return EXIT_FAILURE; @@ -35,9 +47,7 @@ int main(int argc, char** argv) { return EXIT_FAILURE; } - // print results cout << circuit.result(); - return EXIT_SUCCESS; } -- cgit v1.2.3