Writing .csv files from C++

前端 未结 6 762
走了就别回头了
走了就别回头了 2020-12-23 11:18

I\'m trying to output some data to a .csv file and it is outputting it to the file but it isn\'t separating the data into different columns and seems to be outputting the da

6条回答
  •  借酒劲吻你
    2020-12-23 11:39

    Here is a STL-like class

    File "csvfile.h"

    #pragma once
    
    #include 
    #include 
    
    class csvfile;
    
    inline static csvfile& endrow(csvfile& file);
    inline static csvfile& flush(csvfile& file);
    
    class csvfile
    {
        std::ofstream fs_;
        const std::string separator_;
    public:
        csvfile(const std::string filename, const std::string separator = ";")
            : fs_()
            , separator_(separator)
        {
            fs_.exceptions(std::ios::failbit | std::ios::badbit);
            fs_.open(filename);
        }
    
        ~csvfile()
        {
            flush();
            fs_.close();
        }
    
        void flush()
        {
            fs_.flush();
        }
    
        void endrow()
        {
            fs_ << std::endl;
        }
    
        csvfile& operator << ( csvfile& (* val)(csvfile&))
        {
            return val(*this);
        }
    
        csvfile& operator << (const char * val)
        {
            fs_ << '"' << val << '"' << separator_;
            return *this;
        }
    
        csvfile& operator << (const std::string & val)
        {
            fs_ << '"' << val << '"' << separator_;
            return *this;
        }
    
        template
        csvfile& operator << (const T& val)
        {
            fs_ << val << separator_;
            return *this;
        }
    };
    
    
    inline static csvfile& endrow(csvfile& file)
    {
        file.endrow();
        return file;
    }
    
    inline static csvfile& flush(csvfile& file)
    {
        file.flush();
        return file;
    }
    

    File "main.cpp"

    #include "csvfile.h"
    
    int main()
    {
        try
        {
            csvfile csv("MyTable.csv"); // throws exceptions!
            // Header
            csv << "X" << "VALUE"        << endrow;
            // Data
            csv <<  1  << "String value" << endrow;
            csv <<  2  << 123            << endrow;
            csv <<  3  << 1.f            << endrow;
            csv <<  4  << 1.2            << endrow;
        }
        catch (const std::exception& ex)
        {
            std::cout << "Exception was thrown: " << e.what() << std::endl;
        }
        return 0;
    }
    

    Latest version here

提交回复
热议问题