简体   繁体   English

如何将列名设置为csv文件 - c ++

[英]how to set column name to csv file - c++

I am writing some string data to a .csv file using ofstream like 我正在使用ofstream将一些字符串数据写入.csv文件

out << string-A << "," <<  string-B << "\n" ;

But, I could not find a way to set the column name of the .csv file. 但是,我找不到设置.csv文件的列名的方法。

I mean, I want to give column name of string-A to (say) Col-1 and string-B to (say) Col-2. 我的意思是,我想将字符串-A的列名称(比如说)Col-1和字符串-B给(比方说)Col-2。

How to do that in c++ (I don't want to use any libraries). 如何在c ++中做到这一点(我不想使用任何库)。 I am working in windows environment. 我在Windows环境中工作。

Edit: I want format like: 编辑:我希望格式如下:

Col-1         col-2
1              4
2              5
3              6
4              7

Column names are headings not cell values ? 列名是标题而不是单元格值?

你可以先这样做:

out << setiosflags(ios::left) << setw(20)<< "ROW-1" << setiosflags(ios::left) << setw(20) << "ROW-2" << "\n";
out << "Col-1" << "," << "col-2" << "\n";
out << "1"     << "," << "4"     << "\n";
out << "2"     << "," << "5"     << "\n";
out << "3"     << "," << "6"     << "\n";
out << "4"     << "," << "7"     << "\n";

Since it is a text file you can write every line, independent of the data (ie if it is a header/column name or data row). 由于它是一个文本文件,您可以独立于数据(即,如果它是标题/列名称或数据行)编写每一行。

However, high likely you want to write the data as a loop, something like: 但是,您可能希望将数据写为循环,例如:

out << "Col-1" << "," << "col-2" << "\n";
for (var x = 1; x < 5; x++)
{
    out << x.ToString() << "," << (x + 3).ToString() << "\n";
}

Also when reading the data, you want to skip the colum names. 此外,在读取数据时,您希望跳过列名称。 To do this, you can skip the first line by default, or you use a 'comment' character like # and skip it dynamically. 为此,您可以默认跳过第一行,或者使用#等“注释”字符并动态跳过它。 In this case the output of the file should look like: 在这种情况下,文件的输出应如下所示:

#Col-1         col-2
1              4
2              5
3              6
4              7

and the code to produce this: 以及产生这个的代码:

out << "#Col-1" << "," << "col-2" << "\n";
for (var x = 1; x < 5; x++)
{
    out << x.ToString() << "," << (x + 3).ToString() << "\n";
}

You can write the names just like you the writing the data. 您可以像编写数据一样编写名称。 You will have to do this at start. 你必须在开始时这样做。 However depending upon the width of data string you will need to do some formatting so that data is correctly aligned below Col-1 and Col-2. 但是,根据数据字符串的宽度,您需要进行一些格式化,以便在Col-1和Col-2下正确对齐数据。

out <<"Col-1"<< " "<<"Col-2"<< "\n" ;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM