-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathMatrixReaderWriter.cpp
110 lines (82 loc) · 2.48 KB
/
MatrixReaderWriter.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
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
#include "MatrixReaderWriter.h"
#include <string>
MatrixReaderWriter::MatrixReaderWriter(double* data, int rowNum, int columnNum) {
this->data = new double[columnNum * rowNum];
for (int i = 0; i < (columnNum * rowNum); i++) this->data[i] = data[i];
this->rowNum = rowNum;
this->columnNum = columnNum;
} //end MatrixReaderWriter(double* data, int rownum, int columnNum)
MatrixReaderWriter::~MatrixReaderWriter() {
if (this->data != NULL) delete[] data;
}
MatrixReaderWriter::MatrixReaderWriter(const char* fileName) {
this->data = NULL;
load(fileName);
}//end MatrixReaderWriter(const char* fileName)
void MatrixReaderWriter::load(const char* fileName) {
ifstream datafile(fileName);
string line;
int lineCounter = 0;
//Count lines
if (datafile.is_open()) {
while (!datafile.eof())
{
getline(datafile, line);
if (line.length() != 0)
if (line.at(0) != '#')
lineCounter++;
}//end while
datafile.close();
}//end if
else {
cout << "Unable to open file";
}
int columnCounter = 0;
ifstream datafile2(fileName);
if (datafile2.is_open()) {
getline(datafile2, line);
while (line.at(0) == '#')
getline(datafile2, line);
for (int i = line.find_first_not_of(" ,"); i <= line.find_last_not_of(" ,"); i++)
if ((line.at(i) == ' ') || (line.at(i) == ','))
columnCounter++;
datafile2.close();
columnCounter++;
}
rowNum = lineCounter;
columnNum = columnCounter;
if (data != NULL) delete[] data;
data = new double[rowNum * columnNum];
ifstream datafile3(fileName);
lineCounter = 0;
if (datafile3.is_open()) {
getline(datafile3, line);
while (line.at(0) == '#')
getline(datafile3, line);
while ((!datafile3.eof()) && (line.length() > 0)) {
int index = line.find_first_not_of(" ,");
for (int i = 0; i < columnCounter; i++) {
string number = line.substr(index, line.find(" ", index + 1) - index + 1);
double num = strtod((char*)&number[0], NULL);
data[lineCounter * columnNum + i] = num;
index = line.find(" ", index + 1);
}//end for i
getline(datafile3, line);
lineCounter++;
}//end while
datafile3.close();
}
} //end load(string filename)
void MatrixReaderWriter::save(const char* fileName) {
ofstream myfile;
myfile.open(fileName);
myfile << "#Created by C++ matrix writer.\n";
for (int i = 0; i < (rowNum); i++) {
for (int j = 0; j < columnNum; j++) {
myfile << data[i * columnNum + j] << " ";
}//end for j
myfile << endl;
}//end for i
myfile << endl;
myfile.close();
} //end save(string filename)