简体   繁体   English

为什么只有第一行打印在csv文件中?

[英]Why is only the first line printed in csv file?

Using the code below the output gets printed like this: 使用下面的代码,输出如下所示:

1     20
3     21
4     45
5     55 

which is correct, but, while printing it in a csv file it gets printed like this(below) even though codes for printing and writing in csv file are inside the same brackets(same place), 这是正确的,但是,即使在csv文件中进行打印和写入的代码位于相同的括号内(相同位置),当在csv文件中进行打印时,它仍会像下面这样被打印

1     20

which means only the first line is printed. 这意味着只打印第一行。 Why is it not printing the remaining other lines in the csv file ? 为什么不打印csv文件中的其他行? Is there any difference between printing the output and writing it in a csv file in c++ ? 打印输出并将其写入c ++中的csv文件之间有什么区别吗?

This is the block of code : 这是代码块:

ofstream outfile;
double average = (((double) total) / num);
cout << lFraction << " , " << arraySize << " " << average << endl;
outfile.open("results1.csv");
outfile << arraySize << " , " << average << endl ;
outfile.close();

Every time you open the file that deletes the existing contents of the file. 每次打开文件时,都会删除该文件的现有内容。

You have two options: 您有两种选择:

  • Open the file once, write all the results, and then close it. 一次打开文件,写入所有结果,然后将其关闭。
  • Use the app end flag so that the file contents aren't deleted and new data is written at the end: outfile.open("results1.csv", ios::app); 使用app结束标志,这样就不会删除文件内容并在末尾写入新数据: outfile.open("results1.csv", ios::app);

The first option is recommended because constantly opening and closing the same file wastes time. 建议使用第一个选项,因为不断打开和关闭同一文件会浪费时间。

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

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