Writing in files

I would like to write in files like using Fortran language. I mean, in c++, there are no natural spaces between variables when you write them into a file. And when I insert normal spaces using " ", it doesn't look great because the order of magnitude of this variables change between columns and rows, and this gives the files bad aesthetic and maybe could induce bugs when reading this data with some other program. Can someone help me?

Thanks!
Last edited on
You can either use the older C-style printf() or the C++ stream manipulators setw(), setprecision() etc. In particular, setw() - see http://www.cplusplus.com/reference/iomanip/setw/ - will control column width.

The following C++ and fortran codes produce exactly the same output: column width 8, with one space between columns.

C++
1
2
3
4
5
6
7
8
9
10
#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
   int A[] = { 1, 12, 123, 1234, 12345, 123456, 1234567 };

   for ( int i : A ) cout << setw( 8 ) << i << ' ';
}


fortran
1
2
3
4
5
6
7
program main
   implicit none
   integer, allocatable :: A(:)
      A = (/ 1, 12, 123, 1234, 12345, 123456, 1234567 /)

   write( *, "( 7( I8, 1X ) )" ) A
end program main


       1       12      123     1234    12345   123456  1234567 
Last edited on
Thank you!!

Problem solved!
Topic archived. No new replies allowed.