Summary Files Commits Branches @commit @diff @stats
path: root / Year 1 / Object-oriented Programming / 02-Practice-01.02.2022.cpp
blob: 7c0382a56bb5d28357868d0346a2294fc6e1efa8 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
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();
}