-
Notifications
You must be signed in to change notification settings - Fork 1
/
data_reader_class_buggy.cpp
58 lines (44 loc) · 1.36 KB
/
data_reader_class_buggy.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
#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);
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();
return true;
}
double calculateAverage() const {
double sum = 0.0;
for (double value : columnData) {
sum += value;
}
return sum / columnData.size();
}
};
int main() {
std::string filename = "datacsv"; // Replace "data.csv" with the path to your CSV file
CSVReader reader(filename)
// Note that this is not ideal - readData() should be part of the constructor, but we leave it here for now
reader.readData();
double average = reader.calculateAverage();
std::cout << "Average value of the second column: " << average << std::endl;
return 0;
}