I happened to run across a code example for reading text from a file as follows:
int i;
char *fileName = "text.txt";
ifstream fin(fileName);
while (fin >> i)
{
do something;
}
This code actually opens and reads space-delimited text, but I don’t understand how it works. How does the file get opened without an “open” or “read” command? Is there a way to rewind back to the beginning of the file? I’m trying to create a dynamically allocated array, which I don’t know how to do until after I’ve counted through the file for the number of scores.
The
ifstreamconstructor will open the file.Use
seekg(). If the EOF has been reached then you need to callclear()before callingseekg().If permitted, you could use
std::vectorto store the text read which would avoid having to read the contents of the file twice.