Myself and everyone else seems to have given in on the old thread, so I have abandoned the method I was using last time with functions and gone for a slightly easier route.
I need to write my array of structures to a file, and then write them back in again at a later stage. The code I am using is in the middle of main() in the 'switch' statement
However, suprise suprise, its still giving me trouble and I can't get it to work
Can anyone see where this is going wrong?
I really really need to get this working. I would be eternaly grateful if anyone could sort this out for me. I have been working on this section for over 3 days now......its inhumaine...heh.
Thank you
Code:
#include <iostream>
#include <fstream>
using namespace std;
struct StockItem
{
int code;
char desc[20];
float price;
}stock[125];
void disp_menu(void);
struct StockItem enter_data();
void see_stock(StockItem stock[125], int num_items);
main()
{
int ans, ctr;
int num_items = 0;
FILE *item_file = NULL;
do
{
do
{
disp_menu();
cin >> ans;
} while ((ans<1) || (ans>6));
switch (ans)
{
case 1:
stock[num_items] = enter_data();
num_items++;
break;
case 2:
see_stock(stock, num_items);
break;
case 3: {
item_file = fopen("items.txt", "ab");
for (ctr=0;ctr<125;++ctr)
{
fwrite(&stock[ctr], sizeof(StockItem), 3, item_file);
}
fclose(item_file);
break; }
case 4: {
item_file = fopen("items.txt", "rb");
for (ctr=0;ctr<125;++ctr)
{
fread(&stock[ctr], sizeof(StockItem), 3, item_file);
}
fclose(item_file);
break; }
default:
break;
}
}while (ans!=5);
return 0;
system("PAUSE");
return 0;
}
void disp_menu()
{
cout << "\n*** The Corner Shop ***\n\n";
cout << "Select an option: \n\n";
cout << "\t1. Enter new stock " << endl;
cout << "\t2. See current stock " << endl;
cout << "\t3. Save stock to disk " << endl;
cout << "\t4. Load stock from disk " << endl;
cout << "\t5. Exit \n" << endl;
cout << "option> ";
}
StockItem enter_data()
{
StockItem stock_item;
cout << "\n\nWhat is the product code: ";
cin >> stock_item.code;
cout << "What is the product description: ";
fflush(stdin);
cin.getline(stock_item.desc, 20);
cout << "What is the product price: ";
cin >> stock_item.price;
return (stock_item);
}
void see_stock(StockItem stock[125], int num_items)
{
int ctr;
char ret;
cout << "\n\nHere is the stock listing:\n\n";
for (ctr = 0; ctr < num_items; ++ctr)
{
cout << "Item " << ctr+1 << endl;
cout << "Product Code: " << stock[ctr].code << endl;
cout << "Product Description: " << stock[ctr].desc << endl;
cout << "Price: " << stock[ctr].price << endl;
cout << "------------------------------------------------\n";
}
}