Подтвердить что ты не робот

Запись CSV файлов из С++

Я пытаюсь вывести некоторые данные в CSV файл, и он выводит его в файл, но он не разделяет данные на разные столбцы и, кажется, выводит данные некорректно.

    ofstream Morison_File ("linear_wave_loading.csv");         //Opening file to print info to
    Morison_File << "Time Force(N/m)" << endl;          //Headings for file
    for (t = 0; t <= 20; t++) {
      u = sin(omega * t);
      du = cos(omega * t); 
      F = (0.5 * rho * C_d * D * u * fabs(u)) + rho * Area * C_m * du; 

      cout << "t = " << t << "\t\tF = " << F << endl;
      Morison_File << t;                                 //Printing to file
      Morison_File << F;

    }

     Morison_File.close();

Время и сила (Н/м) находятся в столбцах A и B соответственно, но значения t и F печатают первую строку.

Каков синтаксис для их разделения для печати t в столбцы A и F в столбец B?

4b9b3361

Ответ 1

В CSV файле нет ничего особенного. Вы можете создать их с помощью текстового редактора, просто следуя основным правилам. Используемый разделитель RFC 4180 (tools.ietf.org/html/rfc4180) - это запятая ',' не точка с запятой ';'. Такие программы, как MS Excel, ожидают запятую как разделитель.

Есть несколько программ, которые обрабатывают запятую как десятичную и полуколонную в качестве разделителя, но они технически находятся за пределами "принятого" стандарта для файлов формата CSV.

Итак, создавая CSV, вы создаете свой поток и добавляете свои строки так:

#include <iostream>
#include <fstream>
int main( int argc, char* argv[] )
{
      ofstream myfile;
      myfile.open ("example.csv");
      myfile << "This is the first cell in the first column.\n";
      myfile << "a,b,c,\n";
      myfile << "c,s,v,\n";
      myfile << "1,2,3.456\n";
      myfile << "semi;colon";
      myfile.close();
      return 0;
}

Это приведет к созданию файла CSV, который будет выглядеть при открытии в MS Excel:

Image of CSV file created with C++

Ответ 2

Измените

Morison_File << t;                                 //Printing to file
Morison_File << F;

To

Morison_File << t << ";" << F << endl;                                 //Printing to file

a, также будет делать вместо <

Ответ 3

Вот класс, похожий на STL

Файл "csvfile.h"

#pragma once

#include <iostream>
#include <fstream>

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<typename T>
    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;
}

Файл "main.cpp"

#include "csvfile.h"

int main()
{
    try
    {
        csvfile csv("MyTable.csv"); // throws exceptions!
        // Hearer
        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;
}

Последняя версия здесь

Ответ 4

Вы должны ";" разделитель, CSV = > Значение разделителя запятой

 ofstream Morison_File ("linear_wave_loading.csv");         //Opening file to print info to
    Morison_File << "'Time'; 'Force(N/m)' " << endl;          //Headings for file
    for (t = 0; t <= 20; t++) {
      u = sin(omega * t);
      du = cos(omega * t); 
      F = (0.5 * rho * C_d * D * u * fabs(u)) + rho * Area * C_m * du; 

      cout << "t = " << t << "\t\tF = " << F << endl;
      Morison_File << t << ";" << F;

    }

     Morison_File.close();