#include <iostream>
#include <string>
#include <fstream>
#include <stdlib.h>
usingnamespace std;
int main()
{
int n = 10;
ofstream outFile( "vectors.txt", ios::out);
//exit program if unable to create file
if(!outFile)
{
cerr << "File could not be opened" << endl;
exit( 1 );
}
//write out the size of vector
outFile << "Size: " << n << endl;
//create vector1 with N random elements
outFile << "Vector1: " ;
for (int i = 0 ; i < n ; i++) outFile << rand()%n << ' ';
outFile << endl;
//create vector2 with N random elements
outFile << "Vector2: " ;
for (int i = 0 ; i < n ; i++) outFile << rand()%n << ' ';
outFile << endl;
return 0;
}
This I have this code that will display the vectors. However, I keep getting sig faults:
Why do you have i > 10 at lines 25 and 33? for (int i = 0 ; i > 10 ; i++)
Since i starts at 0, it is definitely not bigger than 10, the condition is false and the loop doesn't execute.
Also, vector1 and vector2 are uninitialised pointers. They may not be dereferenced. Hence vector1[i] and vector2[i] are errors.
I switched around the i > 10 and forgot to switch it back. How would I deference them? Our prof gave us the first file and then the first part of the second and told us to finish it. So really, I guess I don't know why you have to use pointers in the first place here and I don't know how to deference them.
//write out the size of vector
outFile << "Size: " << n << endl;
In the second program you need to read and make use of this information. inFile >> n;
Now you know how many elements there are. So that can be used in two important ways.
1. allocate enough storage to hold the data you will be reading.
vector1 = newint[n];
2. use that value to control the loop
for (int i = 0 ; i < n; i++)
Since vector1 is now a valid pointer it can be used as you originally planned, to store each value read in from the file.
Okay that worked, but how does the in file know that n is the size? I realize that n is initialized as 10 in the output file, but when it is written to the text there is no reference to n at all, just a solid 10.
It doesn't "know". It is up to you as the programmer to match the code that is written to interpret the contents of the file according to your knowledge about the structure of the data in the file.
Here's an example of the file vectors.txt, it looks like this: Size: 10
Vector1: 1 7 4 0 9 4 8 8 2 4
Vector2: 5 5 1 7 1 1 5 2 7 6
The first line has the word "Size:" followed by some integer value. So you design the second program in such a way as to make use of your knowledge about the meaning of the data contained in the file.