-
Notifications
You must be signed in to change notification settings - Fork 1
/
data_reader_class.cpp
66 lines (53 loc) · 1.54 KB
/
data_reader_class.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
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <string>
class CSVReader {
private:
std::string filename;
std::vector<double> columnData;
public:
CSVReader(const std::string& filename) : filename(filename) {}
bool readData() {
std::ifstream file(filename);
if (!file) {
std::cerr << "Failed to open the file." << std::endl;
return false;
}
std::string line;
while (std::getline(file, line)) {
std::istringstream ss(line);
std::string cell;
// Skip the first column
if (std::getline(ss, cell, ',') && std::getline(ss, cell, ',')) {
double value;
std::istringstream(cell) >> value;
columnData.push_back(value);
}
}
file.close();
if (columnData.empty()) {
std::cerr << "No data found in the second column." << std::endl;
return false;
}
return true;
}
double calculateAverage() const {
double sum = 0.0;
for (double value : columnData) {
sum += value;
}
return sum / columnData.size();
}
};
int main() {
std::string filename = "data.csv"; // Replace "data.csv" with the path to your CSV file
CSVReader reader(filename);
if (!reader.readData()) {
return 1;
}
double average = reader.calculateAverage();
std::cout << "Average value of the second column: " << average << std::endl;
return 0;
}