Why does my file operation code write random data over the first two numbers I store in the file.
The code compiles and runs without error messages, but
I try to store the vector [0 0 0 0 0] and instead I get [20520 2414 0 0 0].
I am using linux if that makes a difference.
#include <vector.h>
#include <fstream.h>
void write_to_file(const char * filename, vector<short> v)
{
//const char * filename = "/home/johnson/data/data.txt";
ofstream outf(filename);
for(long i=0;i<v.size();i++)
{
outf << v[i];
outf << " ";
}
outf.close();
}
vector<short> read_from_file(const char * filename)
// there is probably a better way to write this function
{
vector<short> v;
//const char * filename = "/home/johnson/data/data.txt";
ifstream inf(filename);
for(long i=0;i<v.size();i++)
{
inf >> v[i];
}
inf.close();
// I think there should be a return but my compiler doesn't give me an error
}
void testVector(vector<short> a)
{
cout << "begin testVector | ";
long max = a.size();
for(short i=0;i<max;i++)
{
cout << a[i] << " ";
}
cout << endl;
}
int main()
{
vector<short> newVector;
for(short i=0;i<5;i++) newVector.push_back(0);
testVector(newVector);
write_to_file("/home/johnson/data/data1.txt", newVector);
testVector( read_from_file("/home/johnson/data/data1.txt") );
return(0);
}