C++实验学习@小杰
实验九 文件读写操作
1.从键盘输入一批数值,要求保留3位小数,在输出时上下行小数点对齐。
代码
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
double a, b, c;
cout<<"输入3个数值: ";
cin>>a>>b>>c;
cout<<setiosflags(ios::fixed)<<setprecision(3)
<<setfill(' ')<<setw(10)<<a<<'\n'
<<setfill(' ')<<setw(10)<<b<<'\n'
<<setfill(' ')<<setw(10)<<c<<endl;
system("pause");
return 0;
}
结果
2.构建一个结构体struct student,包括两个成员:id和avescore。构建一个struct student类型的动态数组(new 操作),元素个数由用户输入(要求3个)。输入数据存入数组并显示出来({1,5;2,8;3,10})使用文本模式通过I/O流把数组内容存入磁盘文件:student.txt从student.txt中读出数据,采用二进制模式存入文件student.bin
代码
#include<iostream>
#include<fstream>
using namespace std;
struct student
{
char id[10];
int avescore;
};
int main()
{
student stud[3]={ "1",5,"2",8,"3",10 };
int i;
ifstream infile("C:\student.txt",ios::binary);
if(!infile)
{
cerr<<"open error!"<<endl;
abort();
}
for(int i=0;i<3;i++)
infile.read( (char *)&stud[i],sizeof(stud[i]));
infile.close();
for(int i=0;i<3;i++)
{
cout<<"NO."<<i+1<<endl;
cout<<"id:"<<stud[i].id<<endl;
cout<<"avescore:"<<stud[i].avescore<<endl;
}
return 0;
}
结果