C++ 如何使用相同的类和方法来读取/写入可变大小的数据
C++ How to use same class and methods for reading/writing variable size data
我写了一个具有读写方法的c ++类。这些方法从 csv 文件读取和写入行。 目前,我已经实现了对具有五个元组(列)的csv文件的读写,例如 - EmpNo,EmpName,地址,部门,经理。 类包含这 5 个元组作为类的成员变量。
所以基本上,在 read() 中,我使用 fstream 读取行并将元组值放入相应的成员变量中。同样,对于写入,我将行数据从用户获取到类成员变量中,并将其写入 csv 文件中。
现在我想使用相同的代码来读取和写入另一个 csv 文件,该文件在上述五个元组中只有两个元组 - EmpNo、EmpName。
我可以考虑维护一个变量来识别我正在读取/写入的 CSV,并相应地在所有代码中都有 if/else。但这看起来并不干净。 使用我的方法用于 read() 的伪代码如下:
read()
{
read EmpNo;
read EmpName;
If (csv_with_5_tuple == true)
{
read Address;
read Department;
read Manager;
}
}
//Here, 'csv_with_5_tuple ' will be set when reading/writing from/to csv file of five tuples.
使用这种方法,我需要在课堂上的任何地方添加"if"条件。
谁能建议我在 c++ 中做到这一点的最佳方法?
你可以为此使用类继承。有伪代码演示了这个想法:
class csv2 {
public:
virtual void read()
{
read EmpNo;
read EmpName;
}
};
class csv5 : public csv2
{
public:
virtual void read()
{
csv2::read();
read Address;
read Department;
read Manager;
}
};
通过使用一些vector
和模板,您可以执行以下操作:
template <typename T>
std::vector<T> csv_read(std::istream& is, const std::vector<std::string T::*>& members)
{
std::vector<T> res;
std::string header;
std::getline(is, header);
while (true) {
T obj;
for (auto m : members) {
is >> obj.*m;
}
if (!is) {
break;
}
res.push_back(obj);
}
return res;
}
用法类似于
const std::vector<std::string Person2::*> members = {&Person2::Name, &Person2::AgeStr};
auto persons = csv_read<Person2>(ss, members);
演示
或者更简单,如果你只使用std::vector<std::vector<std::string>>
:
std::vector<std::vector<std::string>> csv_read(std::istream& is, std::size_t rowCount)
{
std::vector<std::vector<std::string>> res;
std::string header;
std::getline(is, header);
while (true) {
std::vector<std::string> row(rowCount);
for (auto& col : row) {
is >> col;
}
if (!is) {
break;
}
res.push_back(row);
}
return res;
}
用法类似于
auto data = csv_read(ss, 2);
演示
相关文章:
- C++将文本文件中的数据读取到结构数组中
- 为 Sql 服务器实现 odbc 包装器.将数据库数据读取为字符或要求驱动程序将数据转换为 C 类型
- 如何将来自文本文件的数据读取到结构的int阵列中
- 如何将不同长度的数据读取到 2D 数组中
- 从TXT文件到C 的结构向量中的数据读取
- 将sqlite原始数据读取到qbyTearray
- 如何将来自输入TXT文件的数据读取到2 C 数组中
- 使用MQQueue将数据读取到缓冲区中时麻烦
- 在 VC++ 中将类数据读取和写入二进制文件
- 将数据从数据读取器终端获取到GUI(QtCreator)
- C 将数据读取到一个结构,但它跳过了我的一个获取线,使该元素空白
- C++将二进制数据读取到结构
- c++我需要将文件中的数据读取到多维数组中,然后用一种数据类型对数组进行排序.怎样
- 对齐数据:速度取决于恒定数据读取的相对采样大小和采样频率
- 如何将文件中的数据读取到数组中
- 如何使用Visual C++应用程序的完整应用程序数据读取Minidump的应用程序数据
- 如何将csv文件数据读取到数组中
- 用C++将格式化的数值数据读取到数组中
- 正在从文件中将数据读取到结构数组中
- 将分离的数据读取到数组结构c++中