I have this code that supposed to display the values from an array to a text file
#include <iostream>
#include <cstdlib>
#include <fstream>
#include <vector>
using namespace std;
int array[7][4];
fstream file2;
template< typename T > void display( const vector< vector<T> >& matrix )
{
for(int i = 0; i < 7; ++i)
{
for(int j = 0; j < 4; ++j)
{
array[i][j] = matrix[i][j];
file2 << array[i][j] << " ";
}
file2 << "\n";
}
file2 << "\n";
file2.close();
}
template< typename T >
vector< vector<T> > get( const vector< vector<T> >& m, size_t n,
size_t i, size_t j )
{
const size_t N = m.size() ;
vector< vector<T> > slice(n) ;
for( size_t k = 0 ; k < n ; ++k )
for( size_t l = 0 ; l < n ; ++l )
slice[k].push_back( m.at(k+i).at(l+j) ) ;
return slice ;
}
template< typename T > void print( const vector< vector<T> >& m )
{
file2.open( "file.txt", fstream::out);
for( size_t i = 0 ; i < m.size() ; ++i )
{
for( size_t j = 0 ; j < m[i].size() ; ++j )
{
file2 << m[i][j] << " ";
}
file2 << "\n";
}
file2 << "--------------------\n" ;
}
int main()
{
//initialise array to random number not really shown here
//to make the code shorter
int array1[16][16];
vector< vector<int> > matrix(16);
for(int b = 0; b < 16; ++b)
matrix[b].assign( array1[b], array1[b] + 16);
vector< vector<int> > b;
for(int i = 0; i < 4; ++i)
{
b = get(matrix, 8, 8 * ( i/2 != 0 ), 8 * (i % 2));
print(b);
display(b);
}
return 0;
}
Given a 16x16 array it should be divided into 4 blocks of 8x8 and display the result into a text file. No problem on that part. The problem is when I display the values of the array into the file it only displays the last block not all four blocks.
I tried replacing file2
with cout
and everything works fine. I'm able to get the correct output.
I also tried file2.open( "file.txt", fstream::out | ios::app);
also works but everytime I run the program it appends the data already in the file which makes my values redundant.
So my questions are:
How can I display all the values into the file? so that I can get the same output as when I use cout
How can I make sure that everytime I run my program the data in the files get overwritten?Nothing is appended whatsoever.
For example if the file contains the following:1 2 3 4 5 6 7 8
when I run the program several times again it should contain the same thing.
Any tips on how I can solve this. Thanks!