I need to create a function that reads the contents of a file and creates an array from them. I need a counter that tells me the number of numbers on the file so I can use it for the size of the array. Here is where i am stuck, how do I use that counter since the size of the array has to be a constant number, and the counter isnt.
This is what I have so far
Thanks, I tried what you said but I must be doing something wrong cause it still is not working. Maybe I wrote it incorrectly somehow. Here is what i have.
infile.open("number.txt");
if(infile.is_open()) // returns true if file is open
{
while(infile.good()) // loop will continue until eof is reached
{
infile>>number;
count++;
}
}
else
{
cout <<"Error";
}
}
not sure if the infile>>number thing was exactly what you wanted to do there but anyway..
@clarkkent
After the first pass through the file, the stream will be in a failed state, since the end of file was reached. You need to do two things: clear the error flags, and reset the read pointer back to the start of the file.
1 2
infile.clear();
infile.seekg(0,ios::beg);
Also, on the second pass, use either a while-loop or a for-loop, but not both. Currently, all the numbers would be stored in array[0].
Having said that, I'd use a vector instead, if I was given the choice.
Thank you both, clearing and reseting worked.
The problem I guess now is that our professor told us that we could only use what we learn in class for our projects, and we have not touched on the clearing and resseting part. It sucks.
As for vectors he said we would not get into vectors so thats another thing I cant use. :\
Is there another way to approach this without making two passes of the file?
You could use a separate ifstream (e.g. infile2) to open and read the file for the second pass, that way the flags and position will be in a fresh state.