diff options
Added todays practice
1 files changed, 127 insertions, 0 deletions
| -rw-r--r-- | Year 1/Object-oriented Programming/02-Practice-01.02.2022.cpp | 127 |
diff --git a/Year 1/Object-oriented Programming/02-Practice-01.02.2022.cpp b/Year 1/Object-oriented Programming/02-Practice-01.02.2022.cpp new file mode 100644 index 0000000..7c0382a --- /dev/null +++ b/Year 1/Object-oriented Programming/02-Practice-01.02.2022.cpp @@ -0,0 +1,127 @@ +#include <iostream> +#include <fstream> +#include <cstring> + +// Exercise 1 + +void ex1() { + int a, b, c; + std::cin >> a >> b >> c; + + std::ofstream resultFile("result.txt"); + resultFile << (a + b + c) << " " << (a * b * c); + resultFile.close(); + + std::ifstream resultedFile("result.txt"); + int sum, prod; + resultedFile >> sum >> prod; + std::cout << (sum - prod); + resultedFile.close(); +} + +// Exercise 2 + +const int BUFF_SIZE = 1024; + +int strlen(char* const str) { + int ind = 0; + while (str[ind] != '\0') + ind++; + return ind; +} + +int lengthOfFile(std::ifstream& file) { + int len = 0; + char buffer[BUFF_SIZE]; + while (!file.eof()) { + file.getline(buffer, BUFF_SIZE); + len += strlen(buffer); + } + return len; +} + +void ex2() { + std::ifstream resultFile("result.txt"); + std::cout << lengthOfFile(resultFile) << std::endl; + resultFile.close(); +} + +// Exercise 3 + +struct Pair { + unsigned int left; + unsigned int right; +}; + +Pair createPair(unsigned int left, unsigned int right) { + return { left, right }; +} + +Pair readPairFromFile(std::ifstream& inFile) { + unsigned int left, right; + inFile >> left >> right; + return createPair(left, right); +} + +void writePairToFile(std::ofstream& outFile, Pair pr) { + outFile << pr.left << " " << pr.right << std::endl; +} + +void printPair(Pair pr) { + std::cout << "(" << pr.left << "," << pr.right << ")" << std::endl; +} + +const int MAX_REL_SIZE = 25; + +struct Relation { + Pair pairs[MAX_REL_SIZE]; + int size; +}; + +Relation initRelation() { + return { {}, 0 }; +} + +bool addPairToRelation(Relation& rel, Pair pr) { + if (rel.size == MAX_REL_SIZE) + return false; + + rel.pairs[rel.size++] = pr; + + return true; +} + +Relation readRelationFromFile(std::ifstream& inFile) { + Relation rel = initRelation(); + while (!inFile.eof()) + addPairToRelation(rel, readPairFromFile(inFile)); + + return rel; +} + +void writeRelationToFile(Relation rel, std::ofstream& outFile) { + for (int i = 0; i < rel.size; i++) + writePairToFile(outFile, rel.pairs[i]); +} + +void ex3() { + Relation rel = { + { { 0, 1 }, {2, 3}, {5, 5}, {9, 100} }, 4 + }; + std::ofstream outFile("relation.txt"); + writeRelationToFile(rel, outFile); + outFile.close(); + + std::ifstream inFile("relation.txt"); + if (!inFile.is_open()) + std::cout << "Bruh" << std::endl; + + rel = readRelationFromFile(inFile); + for (int i = 0; i < rel.size; i++) + printPair(rel.pairs[i]); + inFile.close(); +} + +int main() { + ex3(); +} |
