C++ txt 文件读取,并写入结构体中的操作
如下所示:
wang18001
li19002
zhao20003
代码如下:
#include#include #include usingnamespacestd; structpeople { stringname; intage; stringid; }p[20]; intmain() { intn=0; ifstreamin("a.txt",ios::in); if(!in.is_open()) { cout<<"Error:openingfilefail"< >p[n].name>>p[n].age>>p[n].id; n++; } //test for(inti=0;i 补充知识:
C语言C++两个版本txt文件读取结构体信息,写入结构体指针中,并以结构体指针形式返回txt文件行数未知
附加功能:采用直接插入排序方法按总成绩进行了降序排序
1、结构体信息如下:
#definesize9 structstudent//学生信息 { longintnumber; charname[size]; intChinese; intmath; intEnglish; inttotalScore; };2、txt文件(student_info.txt)中存储信息如下:
179328何芳芳8910098 179325陈红8610088 179326陆华758090 179324张小仪855794 179327张平809878 179320木子1009689 179329海子9395883、子函数代码
获取txt文件行数:
char*fname="student_info.txt"; ifstreamin(fname); if(!in){cout<<"Nosuchafile"<3.1、C++版本代码如下:
思路:参考C++txt文件读取,并写入结构体中
//利用C++,将文件中的student类型的数据结构信息取出来,放在一个student类型的结构指针中,并将student*返回 intlen;//文件行数全局变量 student*CreateStudentFromFile(char*fname) { ifstreamin(fname); if(!in){cout<<"Nosuchafile"<>s.number>>s.name>>s.Chinese>>s.math>>s.English)//之前一直错误的原因是写成了cin>>就是从键盘输入了!! { s.totalScore=s.Chinese+s.math+s.English; stu[i]=s; ++i; //*stu++=s;//错误,这样代替前两行一定错误!!暂时还不知道为什么?? } in.close(); //----------------------------------------------- returnstu; } 3.1、C语言版本代码如下:
//将*.txt文件中的学生信息存放到学生结构体指针中,并返回该结构体指针 student*CreateStudentFromFile2(char*fname)//C语言的文件就可以Okay!! { FILE*f; f=fopen(fname,"r"); if(!f){cout<<"Nosuchafile"<4、测试代码
#include#include #include #include usingnamespacestd; #definesize9 structstudent { longintnumber; charname[size]; intChinese; intmath; intEnglish; inttotalScore; }; //利用C++,将文件中的student类型的数据结构信息取出来,放在一个student类型的结构指针中,并将student*返回 intlen;//文件行数全局变量 student*CreateStudentFromFile(char*fname) { ifstreamin(fname); if(!in){cout<<"Nosuchafile"< >s.number>>s.name>>s.Chinese>>s.math>>s.English)//之前一直错误的原因是写成了cin>>就是从键盘输入了!! { s.totalScore=s.Chinese+s.math+s.English; stu[i]=s; ++i; //*stu++=s;//错误,这样代替前两行一定错误!!暂时还不知道为什么?? } in.close(); //----------------------------------------------- returnstu; } //将*.txt文件中的学生信息存放到学生结构体指针中,并返回该结构体指针 student*CreateStudentFromFile2(char*fname)//C语言的文件就可以Okay!! { FILE*f; f=fopen(fname,"r"); if(!f){cout<<"Nosuchafile"< j;--k) s[k]=s[k-1]; s[j]=temp; } } } } voidtest0() { cout<<"------C++版本---test0()---将txt中的结构体信息写入到结构体指针中--------"< 以上这篇C++txt文件读取,并写入结构体中的操作就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。