c++ - 使用运算符读取 .CSV 文件 >>

标签 c++ class csv

我有一个类来读取 CSV 文件

class CSVStudentReader {
    ifstream inStream;
public:
    CSVStudentReader(string fileName): inStream(fileName.c_str()) {}
    Student* readNextStudent() {
        if (inStream.good())
        {
            string name;
            float math;
            float english;
            inStream >> name >> math >> english;
            return new Student(name, math, english);//Student is another class
        }
        return NULL;
    }
    ~CSVStudentReader()
    {
        inStream.close();
    }
};

我必须使用这个类来读取 CSV 文件并且没有更改它。但是 CSV 文件由“,”分隔,所以程序在“inStream >> name >> math >> english;”处出错。如何使用这个类?

最佳答案

有很多方法可以做到这一点。一种是创建一个将逗号分类为空格的类。使用 cppreference 中的示例:

#include <locale>
#include <vector>

class csv_whitespace
    : public std::ctype<char>
{
public:
    static const mask* make_table()
    {
        static std::vector<mask> v(classic_table(), classic_table() + table_size);
        v[','] |=  space;
        v[' '] &= ~space;
        return &v[0];
    }

    csv_whitespace(std::size_t refs = 0) : ctype(make_table(), false, refs) { }
};

#include <memory>

class csv_student_reader
{
private:
    std::ifstream file;
public:
    csv_student_reader(std::string path) :
        file{path}
    {
        file.imbue(std::locale(file.getloc(), new csv_whitespace));
    }

    std::unique_ptr<Student> read_next_student()
    {
        std::string name;
        float math;
        float english;

        if (file >> name >> math >> english)
        {
            return new Student{name, math, english};
        }
        return nullptr;
    }
};

编译:

g++-4.8 -std=c++11 -O2 -Wall -Wextra -pedantic -pthread main.cpp && ./a.out

关于c++ - 使用运算符读取 .CSV 文件 >>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18999256/

相关文章:

c++ - 防止意外对象不兼容?

delphi - 如何在我的delphi应用程序中集成类似的diagam功能?

java - 将不同的类实例保存在列表中

c++ - 返回类内结构

linux - BASH - csv 文件中列和行的条件总和

c++ - setsockopt 的错误 22 是什么?

c++ - 改进 InterlockedCompareExchange() 的原子读取

死兔子的C++程序

字符串剥离后的 Python 不需要的空行

python - Pandas Dataframe CSV 导出,如何防止额外的双引号字符