>// I think there should be a return but my compiler doesn't give me an error
Just because your compiler doesn't complain doesn't mean that there's no error.
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
i agree, however this code does work if i just add two extra numbers a the begining of my vector and then ignore the bad data that is written over them. But when I add a return at the end of my read_from_file function I get a compiler error.
Oh, it's all okay then. :rolleyes:
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
>shouldn't this code read and write vectors?
No, and this is why:
vector<short> v;
...
inf >> v[i];
Tell me, what is the size of v? Where do you specify enough information for the vector to know that v[i] should be valid? You don't. What you have is an empty vector, and the subscript operator is an unchecked operation, so it tries to access the ith element of an empty vector, which will always fail no matter what value i has. Compare:
void write_to_file(const char * filename, vector<short> v)
{
ofstream outf(filename);
outf << v.size() <<' '; // Notice the space, it's important
for(long i=0;i<v.size();i++)
{
outf << v[i];
outf << " ";
}
outf.close();
}
vector<short> read_from_file(const char * filename)
{
short size;
ifstream inf(filename);
inf >> size;
vector<short> v(size);
for(long i=0;i<size;i++)
{
inf >> v[i];
}
inf.close();
return(v);
}
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
#include <fstream>
And resist the urge to reply to years-old threads.
Dave Sinkula
long time no c
5,058 posts since Apr 2004
Reputation Points: 2,780
Solved Threads: 314