C++/Help me to fix the bug in my c++ code
Expert: vijayan - 12/25/2011
QuestionHi,
The following function in Turbo C++ (Win XP environment) has been written to return the maximum of the key values (i.itemcode)of records in a binary file.
Problem:- After adding 13 records having keys 1,2 .... up to 13 using another c++ code which calls the function getimax() to get the maximum key value to allot the next key value for the newly added record. But after adding 13 records, the function getimax() starts returning 13, 24833 etc as the current max value. Here is the code:
int getimax()
{
int maxnum=0;
ifstream f;
Inventory i;
f.open("Inv",ios::in);
i.itemcode=0;
f.read((char *)&i,sizeof(i));
while(!(f.eof()))
{
if (i.itemcode>maxnum)
{maxnum=i.itemcode;}
f.read((char *)&i,sizeof(i));
}
f.close();
return maxnum;
}
The structure of i is as follows:
struct Inventory
{
int itemcode;
char des[30];
int stock;
int eoq;
};
AnswerWithout seeing the whole program, I don't know why you get an error after adding precisely 13 records. In any case, you should change:
f.read((char *)&i,sizeof(i));
while(!(f.eof()))
{
// ...
f.read((char *)&i,sizeof(i));
}
To
while( f.read( (char *)&i, sizeof(i) ) )
{
// ...
}
Ideally prefer using formatted i/o over unformatted i/o.