带I / O的C ++结构

时间:2015-11-19 06:51:35

标签: c++ struct io

当我选择选项1并在那里输入信息时。程序无法输出我输入的所有数据(选项4),而是会崩溃。此外,我在txt文件中看不到任何替换。

#include <fstream>
#include <iostream>
#include <string.h>
using namespace std;


struct inventory{
string itemname;
int quantity;
double sales;
double retail;
};


void add();
void display();
void menu();



int main()
{

    cout << "Welcome to inventory data management program" << endl;
    cout <<"Menu:\n";

    menu();


    return 0;
}

void menu(){
char option='a';
cout <<"1.Add new records\n2.Display a record\n3.Change record\n4.Display all record\n5.Prepare a report\n0.Exit\n";
cout<<"Choice: ";
cin>>option;

switch (option){
    case '1':
    add();
    menu();
    break;


    case '4':
    display();
    menu();
    break;


    case '0':
    cout<<"Good bye\n";
    break;

    default:
    cout<<"Invalid input\n";
    menu();
    break;
    }
}

void add(){
    inventory record;
    char again;

    fstream add("inventory.txt", ios::out | ios::binary);

    do {
    //get data
    cin.ignore();
    cout<< "Enter the following data about this item\n";

    cout<<"Item Name: ";
    cin>>record.itemname;

    cout<<"Quantity: ";
    cin>>record.quantity;
    while (record.quantity<0){
        cout<<"Invalid output. Quantity: ";
        cin>>record.quantity;
    }

    cout<<"Wholesales cost: ";
    cin>>record.sales;
    while (record.sales<0){
        cout<<"Invalid output. Wholesales Cost: ";
        cin>>record.sales;
    }

    cout<<"Retail Cost: ";
    cin>>record.retail;
    while (record.retail<0){
        cout<<"Invalid output. Retail Cost: ";
        cin>>record.retail;
    }
    //write the content to the file
    add.write(reinterpret_cast<char *>(&record),sizeof(record));

    cout<<"Add again?[Type Y to add]: ";
    cin>>again;
    cin.ignore();
} while(again == 'Y' || again =='y');

//close stream
add.close();
}



void display(){

char again;
fstream in;
inventory record;
//open file.
in.open("inventory.txt", ios::in | ios::binary);

//check io
if (!in){
    cout<<"I/O ERROR";
    return;
}
cout<<"Here are the data in the list: \n\n";
//read
in.read(reinterpret_cast<char *>(&record), sizeof(record));

//display
while (!in.eof()){
    cout<<"Item Name: "<<record.itemname<<"\n";
    cout<<"Quantity: "<<record.quantity<<"\n";
    cout<<"Wholesales Cost: "<<record.sales<<"\n";
    cout<<"Retail Cost: "<<record.retail<<"\n";

    cout<<"\nPress RETURN to see the next record.\n";
    cin.get(again);
    //read the next
    in.read(reinterpret_cast<char *>(&record),sizeof(record));
}

cout<<"All the record has been displayed.\n";
//close stream
in.close();
}

0 个答案:

没有答案