Hello,
I am currently working on a parser for my program but I am having problems with reading from file. Please keep in mind that I am new to C++ and especially streams.
This is how it goes:
1. I open the file, and do a quick parse to count the number of objects defined in it.
2. I create an array to hold the expected number of objects based on the count.
3. I go through the file again to parse it in detail while creating the objects and storing them.
Problem is that this does not work. I used to close the file after the count, reopen it for the reading. But the problem is that it never goes through the read loop. It's as if the pointer is still at the end of the file. To verify this, I switched them around and the same situation happened. Whichever loop is first is fine but the other one does not happen.
So then I resorted to using clear() and seekg() but then my program goes through a major crash (something about Damage after CRT block). I'll be posting here the code in hopes that someone can enlighten me as to what causes the problem.
Code:
Parse(char *Filename)
{
ASSERT(Filename != NULL);
if(Filename == NULL)
{
//handle it later
return;
}
ifstream fin(Filename);
char charline[80];
int nb_figures = 0;
int nCurrentFigure = 0;
//Count the number of figures
if(fin)
{
while(fin.getline(charline, 80, ' '))
{
if(charline[0] == '/' && charline[1] == '/')
fin.ignore(80, '\n'); //Skip the entire line as it is a comment
else
{
if(charline[0] == 'L')
nb_figures++;
else if(charline[0] == 'T')
nb_figures += 3;
else
fin.ignore(80, '\n');
}
}
}
//fin.close();
m_lines = new CLine[nb_figures];
fin.clear(); // forget we hit the end of file
fin.seekg(ios::beg); // move to the start of the file
//fin.open(Filename);
while(fin.getline(charline, 80, ' '))
{
if(charline[0] == '/' && charline[1] == '/')
fin.ignore(80, '\n'); //Skip the entire line as it is a comment
else
{
if(charline[0] == 'L')
{
ParseLine(&fin, nCurrentFigure);
nCurrentFigure++;
}
else if(charline[0] == 'T')
{
ParseTriangle(&fin, nCurrentFigure);
nCurrentFigure += 3;
}
else
fin.ignore(80, '\n');
}
}
fin.close();
}
I did not provide all the info as the code is very long. I include <fstream> and I have been using the std namespace.
Thanks in advance