从 C++ 写入 .csv 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25201131/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 11:16:39  来源:igfitidea点击:

Writing .csv files from C++

c++csv

提问by user3460758

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 data incorrectly.

我正在尝试将一些数据输出到 .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();

Time and Force(N/m) are in columns A and B respectively but the t and F values are both printing the first row.

时间和力(N/m)分别在 A 列和 B 列中,但 t 和 F 值都打印第一行。

What is the syntax to separate them to print t into column A and F into column B?

将它们分开以将 t 打印到 A 列和 F 到 B 列的语法是什么?

回答by BHawk

There is nothing special about a CSV file. You can create them using a text editor by simply following the basic rules. The RFC 4180 (tools.ietf.org/html/rfc4180)accepted separator is the comma ',' not the semi-colon ';'. Programs like MS Excel expect a comma as a separator.

CSV 文件没有什么特别之处。只需遵循基本规则,您就可以使用文本编辑器创建它们。RFC 4180 (tools.ietf.org/html/rfc4180)接受的分隔符是逗号“,”而不是分号“;”。像 MS Excel 这样的程序需要逗号作为分隔符。

There are some programs that treat the comma as a decimal and the semi-colon as a separator, but these are technically outside of the "accepted" standard for CSV formatted files.

有一些程序将逗号视为小数,将分号视为分隔符,但这些在技术上超出了 CSV 格式文件的“接受”标准。

So, when creating a CSV you create your filestream and add your lines like so:

因此,在创建 CSV 时,您将创建文件流并添加如下行:

#include <iostream>
#include <fstream>
int main( int argc, char* argv[] )
{
      std::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;
}

This will result in a CSV file that looks like this when opened in MS Excel:

这将产生一个在 MS Excel 中打开时看起来像这样的 CSV 文件:

Image of CSV file created with C++

用 C++ 创建的 CSV 文件的图像

回答by Mr.WorshipMe

Change

改变

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

To

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

a , would also do instead of ;

a , 也可以代替 ;

回答by Valdemar_Rudolfovich

Here is a STL like class

这是一个类似 STL 的类

File "csvfile.h"

文件“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;
}

File "main.cpp"

文件“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;
}

Latest version here

最新版本在这里

回答by MiguelAngel_LV

You must ";" separator, CSV => Comma Separator Value

你必须 ”;” 分隔符,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();

回答by ádám Hadar

If you wirte to a .csv file in C++ - you should use the syntax of :

如果您在 C++ 中写入 .csv 文件 - 您应该使用以下语法:

myfile <<" %s; %s; %d", string1, string2, double1 <<endl;

This will write the three variables (string 1&2 and double1) into separate columns and leave an empty row below them. In excel the ; means the new row, so if you want to just take a new row - you can alos write a simple ";" before writing your new data into the file. If you don't want to have an empty row below - you should delete the endl and use the:

这会将三个变量(字符串 1&2 和 double1)写入单独的列,并在它们下方留下一个空行。在 excel 中;表示新行,所以如果你只想换行 - 你也可以写一个简单的“;” 在将新数据写入文件之前。如果你不想在下面有一个空行 - 你应该删除 endl 并使用:

myfile.open("result.csv", std::ios::out | std::ios::app);

syntax when opening the .csv file (example the result.csv). In this way next time you write something into your result.csv file - it will write it into a new row directly below the last one - so you can easily manage a for cycle if you would like to.

打开 .csv 文件时的语法(例如 result.csv)。以这种方式,下次您将某些内容写入 result.csv 文件时 - 它会将其写入最后一行正下方的新行中 - 因此您可以根据需要轻松管理 for 循环。