Export data from an array to a csv file

1
2
3
4
5
6
7
8
9
10
11
12
13
ofstream outfile;
	outfile.open("C:/Users/Saad/Desktop/result.csv");
	for(i=0;i<655;i++)
	{
		for(j=0;j<655;j++)
		{
			if(arr[i][j]!=0)
			{
				outfile<<arr[i][j]<<endl;
			}
		}
	}
	outfile.close();


Current OUTPUT:
on running this program the data is exported, but every value from arr[i][j] is written in a first column of new row. Like:
1
2
2
16
1
3
2
Desired OUTPUT:
1 2
2 16 1 3 5
3 2

Please provide the solution.
Thanks
Mohd Adnan

Last edited on
Please, edit your post to enclose the code in code tags and be systematic about indentation. See http://www.cplusplus.com/articles/jEywvCM9/
hello keskiverto ,
i have edited the code as per instruction ....
Your topic title states that you want to export the file as a CSV (Comma Separated Values) file yet I see no commas in your desired output.

But in any case if you don't want the values on their own lines why are you printing a new line every time you print a number, wouldn't a space or a comma be a better idea?

What happens if your array is smaller than that "magic number" (655)?
hi
initially in my program i have imported data from excel file and done the desired calculations, now the output is stored in the array 'arr', i have to export this array 'arr' to an excel file,
in my current program the values of each row of the array is exported in a new columm to an excel file, hence the exported data in not useful,
i have to export the array as it is in the excel file.
Move the 'endl' from line 9 to between lines 10 and 11.

Don't forget to put something (like a comma) between outputs. This takes a little thinking, because you want to see:
    1,2,3,4
and not:
    1,2,3,4,

Fortunately, that's a pretty simple fix:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// for each row
for (i=0; ...)
{
  // print first column's element
  outfile << arr[i][0];

  // print remaining columns
  for (j=1; ...)
  {
    outfile << ", " << arr[i][j];
  }

  // print newline between rows
  outfile << endl;
}

Hope this helps.

[edit] Fixed typo
Last edited on
Thank you so much.... :-)
Topic archived. No new replies allowed.