-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTable.cpp
More file actions
84 lines (70 loc) · 2.18 KB
/
Table.cpp
File metadata and controls
84 lines (70 loc) · 2.18 KB
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
#include "Table.hpp"
#include <iostream>
#include <fstream>
// Constructor
Table::Table(const std::string& tableName, const std::vector<std::string>& columnNames)
: name(tableName), columns(columnNames), rows() {}
// Insert a row into the table
void Table::insertRow(const std::vector<std::string>& rowData) {
if (rowData.size() != columns.size()) {
std::cerr << "Row size mismatch!\n";
return;
}
rows.push_back(rowData);
}
// Print the entire table
void Table::printTable() const {
for (const auto& col : columns)
std::cout << col << "\t";
std::cout << "\n";
for (const auto& row : rows) {
for (const auto& value : row)
std::cout << value << "\t";
std::cout << "\n";
}
}
const std::string& Table::getName() const {
return name;
}
// Select and print rows that match a condition
void Table::selectWhere(int columnIndex, const std::string& op, const std::string& value) const {
if (columnIndex < 0 || columnIndex >= static_cast<int>(columns.size())) {
std::cerr << "Invalid column index\n";
return;
}
std::cout << "Results:\n";
for (const auto& col : columns)
std::cout << col << "\t";
std::cout << "\n";
for (const auto& row : rows) {
if (op == "==" && row[columnIndex] == value) {
for (const auto& val : row)
std::cout << val << "\t";
std::cout << "\n";
}
// You can expand this with more operators (>, <, etc.) if needed.
}
}
void Table::saveToFile(const std::string &fileName) const {
std::ofstream file(fileName);
if (!file.is_open()) {
std::cerr<<"Failed to open the file: "<<fileName<<"\n";
return;
}
//write column headers
for (size_t i = 0; i < columns.size(); ++i) {
file<< columns[i] ;
if (i<columns.size() - 1)file<<",";
}
file<<"\n";
// Write each row
for (const auto& row : rows) {
for (size_t i = 0; i < row.size(); ++i) {
file << row[i];
if (i < row.size() - 1) file << ",";
}
file << "\n";
}
file.close();
std::cout << "Table \"" << name << "\" saved to " << fileName << "\n";
}