实验要求:
实验代码;
#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <fstream>
#include <iomanip>
#include <ctype.h>
using namespace std;
//图书结构体
struct Book {
double price;
char name[50];
char Locate[15];
}book[200];
int sum = 0;
int flag = 0;
string path = "book.txt";
//写入文件函数 将更新后的数据写入指定文件
void Out_to_File()
{
int n = 0;
ofstream file;
file.open(path, ios::out | ios::trunc);
if (!file.is_open())
{
cout << "You have failed to open the file!" << endl;
exit(1);
}
while (n < sum)
{
file << book[n].Locate << "\t" << book[n].name << "\t" << book[n].price << endl;
n++;
}
file.close();
}
//读取文件函数 将txt文件中的数据导入结构体
void Read_File()
{
int n = 0;
char first_line[200];
char second_line[200];
ifstream myfile(path, ios::in);
if (!myfile.is_open())
{
cout << "Sorry You Have Failed to Open the File!" << endl;
exit(1);
}
else
{
myfile.getline(first_line, 200);
myfile.getline(second_line, 200);
while (!myfile.eof())
{
myfile >> book[n].Locate >> book[n].name >> book[n].price;
n++;
}
}
sum = n;
cout << "一共有" << sum << "个图书的信息" << endl;
myfile.close();
flag = 1;
cout << "You have read the file successfully!" << endl;
}
//显示函数 将图书信息打印在显示屏上
void Display_Information() {
if (!flag) {
cout << "\t\t当前未录入图书信息,请先录入。\n" << endl;
exit(0);
}
else {
cout << "\t书号\t\t\t\t书名\t\t\t\t价格" << endl;
for (int i = 0; i < sum; i++)
{
cout << book[i].Locate << "\t\t\t" << book[i].name << "\t\t\t" << book[i]