You are here:

C++/Help me to fix the bug in my c++ code

Advertisement


Question
Hi,

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;
};

Answer
Without 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.

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


vijayan

Expertise

my primary areas of interest are generic and template metaprogramming, STL, algorithms, design patterns and c++11. i would not answer questions about gui and web programming.

Experience

about 15 years or so

Education/Credentials
post graduate engineer

©2016 About.com. All rights reserved.