-
Notifications
You must be signed in to change notification settings - Fork 0
/
cpa_lab_7_3_7_(1)-B.cpp
82 lines (60 loc) · 1.94 KB
/
cpa_lab_7_3_7_(1)-B.cpp
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
#include <iostream>
#include <fstream>
#include <stdexcept>
#include <sys/stat.h>
using namespace std;
class Matrix{
private:
int matrix[2][2];
public:
int GetMatrixElement(int arrayIndex, int elementIndex);
void LoadMatrix(string path);
void SaveMatrix(string path);
};
bool IsFileExists (string path) {
struct stat buffer;
return (stat (path.c_str(), &buffer) == 0);
}
void Matrix::LoadMatrix(string path){
if(!IsFileExists(path))
throw runtime_error("File not found at: " + path);
ifstream iFile (path);
if(!iFile)
throw runtime_error("No rights to read from file: " + path);
iFile >> matrix[0][0] >> matrix[0][1] >> matrix[1][0] >> matrix[1][1];
iFile.close();
}
void Matrix::SaveMatrix(string path){
if(!IsFileExists(path))
throw runtime_error("File not found at: " + path);
ofstream oFile (path);
if(!oFile){
throw runtime_error("No rights to write to file: " + path);
}
oFile << matrix[0][0] << " " << matrix[0][1] << endl << matrix[1][0] << " " << matrix[1][1];
oFile.close();
}
int Matrix::GetMatrixElement(int arrayIndex, int elementIndex){
if(arrayIndex < 0 || arrayIndex >= 2 || elementIndex < 0 || elementIndex >= 2)
throw invalid_argument("Index out of range");
return this->matrix[arrayIndex][elementIndex];
}
int main()
{
string path;
Matrix matrix;
cout << "Enter path to file for read matrix:" << endl;
getline(cin, path);
try{
matrix.LoadMatrix(path);
cout << "Matrix:" << endl << matrix.GetMatrixElement(0, 0) << " " << matrix.GetMatrixElement(0, 1) <<
endl << matrix.GetMatrixElement(1, 0) << " " << matrix.GetMatrixElement(1, 1) << endl;
cout << "Enter path to file for save matrix:" << endl;
getline(cin, path);
matrix.SaveMatrix(path);
}
catch (const exception& e){
cout << e.what() << endl;
}
return 0;
}