Hello Everyone,
I am trying to write a float array to a ‘*.dat’ file. I am only partially successful and would appreciate some help and explanation of what is going on wrong.
1) First setw command does not seem to work.
2) I can write float array to output file using one element at a time. But, I would like to write everything using a single operation.
First I initialize my float array
1 2 3 4 5 6
|
float * sliceProfile = new float[300];
then I calculate it
// Displaying calculated slice profile
for(int i = 0; i != slabNz; ++i){
std::cout << std::setw(7) << sliceProfile[i] <<std::endl;
}
|
and it appears like this:
1 2 3 4 5 6 7 8
|
0.00302053
0.00333289
0.0035445
0.00363793
0.00360763
0.00345606
0.00319472
0.00284252
|
Here, there are more than 7 fields in output. So, I am not able to use setw as I wanted.
then try to save it using one of two possible ways:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
// This does not work
std::ofstream outfile("OutputFile.dat");
// write to outfile
outfile.write ((char*)&sliceProfile, sizeof(float));
outfile.close();
// This works as desired
std::ofstream outfile("OutputFile2.dat");
// write to outfile
for(int i = 0; i != slabNz; ++i){
outfile << std::setw(4) << sliceProfile[i] <<std::endl;
}
outfile.close();
|
The file saved using the first method gives contains something like this:
|
0.0000000.0000000.0000000.0000000.0000000.0000000.0000000.0000000.0000000.0000000.0000000.0000000.0000000.0000000.0000000.0000000.0000000.0000000.0000000.0000000.0000000.0000000.0000000.0000000.0000000.0000000.0000000.0
|
While the file saved using second method works, I do not want to read using for loop.
Could someone please explain:
1) Why setw is not working as expected:
2) how can I write all elements of a float array using a single operation and not inside the for loop.