c++ - 无法打印 CSV 文件

标签 c++ csv iostream

以下代码编译良好,因此没有语法错误。我无法打印出我读入这段代码的 CSV 文件。我不确定发生了什么,因为这是一个标准程序,但希望能就如何解决这个问题提供一些意见。我希望能够在控制台上打印出 s 的内容。你能看出为什么 s 没有在控制台上打印吗?我错过了什么吗?

#include <cstdlib>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <string.h>
#include <vector>
#include <fstream>
#include<iterator>

struct field_reader: std::ctype<char> {

    field_reader(): std::ctype<char>(get_table()) {}

    static std::ctype_base::mask const* get_table() {
        static std::vector<std::ctype_base::mask>
            rc(table_size, std::ctype_base::mask());

        rc[';'] = std::ctype_base::space;
        return &rc[0];
    }
};


struct Stud{
    double VehicleID;
    double FinancialYear;
    double VehicleType;
    double Manufacturer;
    double ConditionScore;


    friend std::istream &operator>>(std::istream &is, Stud &s) {
        return is >> s.VehicleID >> s.FinancialYear >> s.VehicleType >>      s.Manufacturer >> s.ConditionScore;
    }

    // we'll also add an operator<< to support printing these out:
    friend std::ostream &operator<<(std::ostream &os, Stud const &s) {
        return os << s.VehicleID  << "\t"
                  << s.FinancialYear << "\t"
                  << s.VehicleType    << "\t"
                  << s.Manufacturer   << "\t"
                  << s.ConditionScore;
    }
};

int main(){
// Open the file:
std::ifstream in("VehicleData_cs2v_1.csv");

// Use the ctype facet we defined above to classify `;` as white-space:
in.imbue(std::locale(std::locale(), new field_reader));

// read all the data into the vector:
std::vector<Stud> studs{(std::istream_iterator<Stud>(in)),
 std::istream_iterator<Stud>()};

// show what we read:
for (auto s : studs)
    std::cout << s << "\n";
}

最佳答案

friend std::istream &operator>>(std::istream &is, Stud &s) {
    return is >> s.VehicleID >> s.FinancialYear >> s.VehicleType 
              >> s.Manufacturer >> s.ConditionScore;
}

忽略逗号完全存在的事实。我能想到的最原始的解决方案是

friend std::istream &operator>>(std::istream &is, Stud &s) {
    char comma;
    return is >> s.VehicleID >> comma
              >> s.FinancialYear >> comma
              >> s.VehicleType >> comma
              >> s.Manufacturer >> comma
              >> s.ConditionScore;
}

关于c++ - 无法打印 CSV 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30695519/

相关文章:

C++ - 将一个 ostream 中的数据发送到另一个 ostream

c++ - 自定义数据 iostream

c++ - 无法包装 std::istream,移动后 unique_ptr 不为空

c++ - 精度另外

PHP 拆分逗号分隔值但保留引号

Python 2.7 : Put extracted data from URL in a CSV file

java - 使用 Java 代码从 CSV/XML 文件中提取附加信息

C++ vector 下标超出范围错误 1221

c++ - 与某些库链接时无法捕获异常

c++ - 预先设置 C++ 代码的执行时间