Chào mọi người. Em nghĩ đây là vấn đề nhiều bạn giống em sẽ gặp phải. Nhờ mọi người liệt kê các cách xử lý dùm ạ.
File CSV mỗi dòng có 6 ô dữ liệu, kiểu string string string double double.
Trừ dòng đầu tiên đều là string.
Cách xử lý đề bài yêu cầu là dùng hàm cắt chuỗi rồi set giá trị ban đầu lại.
Employee arr[N];
const vector<string> explode(const string& s, const char& c) {
string buff { "" };
vector<string> v;
for (auto n : s) {
if (n != c)
buff += n;
else if (n == c && buff != "") {
v.push_back(buff);
buff = "";
}
}
if (buff != "")
v.push_back(buff);
return v;
}
1. Vậy set giá trị cho dòng đầu tiên vào mảng thế nào? Nó luôn báo lỗi.
2. Sao không viết tiêu đề riêng để khỏi phải xử lý?
Em xin bổ sung:
1. Một mẫu nhỏ về file CSV
FirstName, LastName, Job, Department, AnnualSalary, EstimatedSalary
a1, a2, a3, a4, 1, 1
b1, b2, b3, b4, 2, 2
c1, c2, c3, c4, 3, 3
2. Một phần đoạn code của em. Nó chạy ok. Tuy nhiên thầy bảo nên viết lại:
Thay vì:
const vector<string> explode(const string& s, const char& c)
Em nên tạo 1 hàm trả về Employee&:
Employee& explode(const string& s, const char& c).
Em chưa hiểu lắm.
const int N = 100;
Employee employees[N]; // Employee is a class
void ReadToArray(Employee arr[], string filename)
{
int i = 0;
ifstream file(filename);
if (file.is_open())
{
string line;
getline(file, line, '\n'); // Mean skip the first line? Right?
while (getline(file, line))
{
vector<string> v = explode(line, ',');
arr[i].setFirstName(v[0]);
arr[i].setLastName(v[1]);
arr[i].setJobTitle(v[2]);
arr[i].setDepartment(v[3]);
arr[i].setAnnualSalary(stod(v[4]));
arr[i].setEstimatedSalary(stod(v[5]));
i++;
}
}
}
void Display(Employee arr[], int size)
{
for (int i = 0; i < size; i++)
{
employees[i].printData();
}
}
int main()
{
ReadToArray(employees, "Employees.csv");
Menu();
return 0;
}