How to print an std::vector in a file: error

I have the following vector that represents my time iterations in the code that I would like to print in a text file for documentation/debugging purposes.
1
2
3
4
5
6
7
8
9
  //initialize the vector to zeros 
   std::vector<double> time(iter_max + 1,0.0);
  // Update time
    time[iter + 1] = time[iter] + dt;
  // print in the terminal:
    //output time stamp
   printf("Iteration = %d    t = %.10f   phi_iter = %d\n", iter, time[iter+1], phi_iter);
...
		

I wrote this function to write out my time stamp into a text file, but I am having the error: "operand types are incompatible ("int" and "int *")"
1
2
3
4
5
6
7
8
9
10
11
12
13
void print1DArrf(char filename[], double arr[], int nArr[]){

	FILE *fptr;
	
	fptr = fopen(filename, "w");
		
	// Get size of the 1D array first.	
	for (int i = 0; i < nArr; i++) { //ERROR
		fprintf(fptr,"%+4.16le\n",arr[i]);
	}
	
	fclose(fptr);
}	
i < nArr;

Above that line, you have a comment saying to get the size of the 1D array first. I presume this step was accidentally skipped. Friendly warning, though, I wouldn't try to use sizeof in this context.

-Albatross
Did you mean
 
void print1DArrf(char filename[], double arr[], int nArr){
?
@helios

Did you mean

void print1DArrf(char filename[], double arr[], int nArr){
?

I don't see what's different about your line? Not sure what you mean ..

Last edited on
@helios
oh..
I see, right I added a [] by accident.
Your function doesn't accept a std::vector as a parameter, it has THREE regular arrays. One C string array, one double array and an int array.
Yeah, I think the function itself might not be correct for printing this vector type. I am now getting:
1
2
3

"message": "no suitable conversion function from \"std::vector<double, std::allocator<double>>\" to \"double *\" exists",
@Furry Guy

Your function doesn't accept a std::vector as a parameter, it has THREE regular arrays. One C string array, one double array and an int array.

I see ..
Why use a C string for a filename when you can use a std::string and C++ filestreams.

A possible declaration (NOT definition) for your function might be:

void print1DVec(const std::string& filename, const std::vector<double>& vec);

Gotta make sure you include <string> and <vector> if you do this.
@Furry Guy

I tried doing something like that but the code runs without printing any time stamp.
You realize that is more than likely due to the function's code you write, right?

C++ has the <chrono> library that can be used to get the current system time that can be used for a time stamp, and a damned accurate one to boot.
@Furry Guy
I see, but it's a bit complicated. I am sort of benchmarking this C++ code to another version in MATLAB and I kinda want the times to be similar for me to compare some results.
Topic archived. No new replies allowed.