Need help producing iterated .csv files with for loops.

Hello All, new member here. Been searching the forum for awhile, and though I'd get on board.

Running Ubuntu 12.10 (if it's necessary information).

The following is a piece of simulation code I'm working on, and it's purpose is to update the particle velocities (within the array 'parvel') through each iteration of the loop. Where can I place the indexing 'i' such that a new .csv file is created with each loop?

for (int i = 0; i < timesteps; i++) {

  pairpart(P,P);	 //Randomize P, display
  compute(parvel,P,g2);	 //Compute collisional pairs, assign
  collide(parvel,P,g2);	 //Collide! Re-adjust velocities.

//Build final velocity vectors into CSV files
  ofstream array2f; ("array2f_.csv");
	for (int i = 0; i < N; i++) {

Last edited on
Your question is somewhat ambiguous since you have two loops, each indexed by i.
Not sure which loop you're referring to.

As it is you will open and write the csv file for each timestep.
Not sure if this is what you want.
In any case, what's going to happen is that that you will open and write to the same file each time through the outer loop.
Are you trying to produce different .csv files?
If so, you need to modify the filename in some manner to make the filenames different.

Ah yes, sorry, the outer loop. As it is now, the same .csv file is re-written each iteration.

"If so, you need to modify the filename in some manner to make the filenames different."

This was exactly my question; I don't know how to do this! A work around I've been using is to put cin.get(); at the end of the loop and just manually re-name the output file after each iteration.
An easy way to do this is with a stringstream.
  stringstream  ss;
  ss << "array2f_" << i << ".csv";  // build the filename (ss.str().c_str());

BTW, it's not a good idea to have nested loops with the same loop variable name.
They do have different scopes, so the compiler can tell them apart, but if you needed to reference the outer loop variable from inside the inner loop, you would have a problem. It also confusing to the reader. :)

Thanks, Abstraction, that worked perfectly! Now I can perform the amount of timesteps required (~1e3), and not go insane with manual file manipulation.

About the indexing value. Up to this point I had been copying/pasting tons of code, and there are some residual...effects.

One more question: how do I specify the location within my file system to store the output .csv's?
Just qualify the filename portion of the filename just as you would any other pathname.

ss << "etc/array2f_" << i << ".csv";  // build the filename 

Topic archived. No new replies allowed.