从C ++编写.csv文件 [英] Writing .csv files from C++
问题描述
我试图输出一些数据到.csv文件,它正在将其输出到文件,但它不是将数据分成不同的列,似乎输出的数据不正确。
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.
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();
时间和力(N / m)分别在A列和B列,但t和F值都在打印第一行。
Time and Force(N/m) are in columns A and B respectively but the t and F values are both printing the first row.
将它们分别打印到列A和F到列B中的语法是什么?
What is the syntax to separate them to print t into column A and F into column B?
推荐答案
CSV文件没有什么特别之处。只需按照基本规则,您就可以使用文本编辑器创建它们。 RFC 4180 (tools.ietf.org/html/rfc4180)接受的分隔符是逗号,不是分号;。像MS Excel这样的程序需要逗号作为分隔符。
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格式文件的已接受标准。
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:
#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;
}
这将导致在MS Excel中打开时看起来像这样的CSV文件:
This will result in a CSV file that looks like this when opened in MS Excel:
这篇关于从C ++编写.csv文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!