0

I am making an inventory management system, its just starting of my program. I have a problem with this code.

When I start program and display objects its works correctly but after that when I again press 2 for display loop didn't break.

 #include<iostream>
 #include<fstream>
 using namespace std;
 class products
 {
char pname[20];
int pid;
int quantity;
int price;
public:
products()
{
    pname[0]='\0';
    pid=NULL;
    quantity=0;
    price=0;
}
void get()
{
    cout<<"Enter Product Name: ";
    cin>>pname;
    cout<<"Enter Product id: ";
    cin>>pid;
    cout<<"Enter Product Quantity: ";
    cin>>quantity;
    cout<<"Enter Product Price: ";
    cin>>price;
}
void display()
{
    cout<<"Product Name: ";
    cout<<pname;
    cout<<"\nProduct id: ";
    cout<<pid;
    cout<<"\nProduct Quantity: ";
    cout<<quantity;
    cout<<"\nProduct Price: ";
    cout<<price<<endl;
}
void sale()
{
    quantity--;
}
 };


 int _tmain(int argc, _TCHAR* argv[])
  {
products p;
int c;
fstream f;
f.open("product.dat",ios::binary|ios::in|ios::out|ios::app);
do{
    cout<<"Enter 1 to add product \n 2 to Display all products";
    cin>>c;
    switch(c)
    {
    case 1:
        p.get();
        f.write(reinterpret_cast<char*>(&p),sizeof(products));
        break;
    case 2:
        f.seekg(0,ios::beg);
        while(!f.eof())
        {
            f.read(reinterpret_cast<char*>(&p),sizeof(products));
            p.display();
        }

        break;
    }
}while(c!=0);

return 0;

}`

Paul Rooney
  • 17,518
  • 8
  • 35
  • 57
  • Unclear, please describe 1-what you want to achieve 2-what the current code does. And why the `stack-overflow` tag ? – kebs May 28 '15 at 12:32
  • Using `eof` as a loop condition is almost always wrong. This is because the eof bit is not set until *after* you try to read a record. Hence with the way you have it now, it will "display" one record at the end which was not read from the file. – Dark Falcon May 28 '15 at 12:33
  • Read this: http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong – Baum mit Augen May 28 '15 at 12:34
  • I want to take input from user and write it into file..and then when user press 2 it display all data stored in file... – DaNial Khalid May 28 '15 at 12:34
  • So what should i use instead of .eof? – DaNial Khalid May 28 '15 at 12:38
  • @DaNialKhalid You check the state of the input operation like `while(f.read(reinterpret_cast(&p),sizeof(products)))`. It's all well described in the answers to the question marked as duplicate. – πάντα ῥεῖ May 28 '15 at 12:52

0 Answers0