C++ :怎样将数据从txt文档中读取出来建立单链表,并输出???
先将建立的单链表的数据存储在txt文件当中,然后再从txt文件中提取出来,将提取出来的数据再建立单链表,并输出。主要是readfile()这个函数不会写,总是出现错误,什么引用内存错误之类的,下面的写的readfile()那个应该有问题。现求救各位高手。还有就是我这程序开头的定义有没有问题,需不需要修改?程序代码如下:程序代码:
#include<iostream> #include<fstream> using namespace std; typedef struct GoodsNode *pointer; //节点指针类型 struct GoodsNode { char name[20]; //商品名称 double number; //商品代码 char address[30]; //商品产地 int price; //商品单价 double stock; //该类商品库存量 pointer next; }; typedef pointer goodslist; // 头指针类型 goodslist head; goodslist initlist() //初始化,建立一个只有头节点的空表 { pointer head; head=new GoodsNode; head->next=NULL; return head; } void savefile() //将数据存储在文件当中 { ofstream save("marketdata.txt",ios::out|ios::app); if(!save) { cout<<"不能保存:marketdata.txt!! "<<endl; system("pause"); exit(1); } pointer G; G=head->next; while(G!=NULL) { save<<'\t'<<G->name<<'\t'<<G->number<<'\t'<<G->address<<'\t'<<G->price<<'\t'<<G->stock<<endl; G=G->next; } save.close(); } goodslist increase() //录入商品 { int num=0,m=0; pointer rear,goods; head=new GoodsNode; rear=head; cout<<"请输入待添加商品的种类数:"; cin>>num; while(m<num) { goods=new GoodsNode; cout<<"商品名称:"; cin>>goods->name; cout<<"商品代码:"; cin>>goods->number; cout<<"商品产地:"; cin>>goods->address; cout<<"商品单价:"; cin>>goods->price; cout<<"商品库存:"; cin>>goods->stock; rear->next=goods; rear=goods; m++; } rear->next=NULL; cout<<"录入完毕!"<<endl; return head; } goodslist readfile() //读取文件中的数据 { pointer head,rear,G; head=new GoodsNode; G=new GoodsNode; rear=head; ifstream read("marketdata.txt",ios::in); if(!read) { cout<<"读取文件失败!!"<<endl; system("pause"); exit(1); } while(read.good()) { read>>G->name>>G->number>>G->address>>G->price>>G->stock; rear->next=G; rear=G; } rear->next=NULL; read.close(); return G; } void display() //输出全部商品信息 { cout<<"名称\t"<<"代码\t"<<"产地\t"<<"单价\t"<<"库存量\t"<<endl; pointer G; G=head->next; while(G!=NULL) { cout<<G->name<<'\t'<<G->number<<'\t'<<G->address<<'\t'<<G->price<<'\t'<<G->stock<<endl; G=G->next; } cout<<endl<<endl; } void AdminMenu() { cout<<"1.录入商品信息\t"<<"2.提取商品信息\t"<<endl; cout<<"3.查看所有商品\t"<<endl; cout<<"请选择所需功能:"; } int main() { char *ch; initlist(); loop: AdminMenu(); int i; cin>>i; switch(i) { case 1: increase(); savefile(); goto loop;break; case 2: readfile();break; case 3: display(); goto loop;break; } return 0; }
[ 本帖最后由 君破浪 于 2012-3-19 19:37 编辑 ]