程序在Dev-C++5.5.3版本运行
结构体的使用
给结构体赋值,打印出结构体中学生姓名,分数,平均分
#include <iostream>
#include <cassert>
#include <algorithm>
#include <vector>
#include <string.h>//不用.h的话可能下面的strcpy用不了
#include <iterator>
using namespace std;
int main()
{
struct Student //声明结构体类型Student
{
char name[20];
float score1;
float score2;
float score3;
}student1, student2; //定义两个结构体类型Student的变量student1,student2
strcpy(student1.name,"小杨");
student1.score1=60;
student1.score2=70;
student1.score3=80;
strcpy(student2.name,"小李");
student2.score1=96;
student2.score2=97;
student2.score3=98;
int a=0;
a= (student1.score1+student1.score2+student1.score3)/3;
cout<<"学生1姓名:"<< student1.name<<endl;
cout<<"科目1:"<< student1.score1<<endl;
cout<<"科目2:"<< student1.score2<<endl;
cout<<"科目3:"<< student1.score3<<endl;
cout<<"科目均分:"<< a<<endl;
a= (student2.score1+student2.score2+student2.score3)/3;
cout<<"学生2姓名:"<< student2.name<<endl;
cout<<"科目1:"<< student2.score1<<endl;
cout<<"科目2:"<< student2.score2<<endl;
cout<<"科目3:"<< student2.score3<<endl;
cout<<"科目均分:"<< a<<endl;
return 0;
}
-----------------------------------------------------------------------------------------------
C++完成对.txt文件读取,打印所有内容到屏幕上:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ifstream in;
in.open("d:\\haha.txt");//文件每层间一定要用双斜杠隔开
if(!in)
{
cout<<"出错啦"<<endl;
return 1;
}
char ch;
while(!in.eof())
{
in.read(&ch,1);
get(a)
cout<<ch;}
}
in.close();
return 0;
}
-----------------------------------------------------------------------------------------------
读出.txt文件中学生姓名,分数,平均分
txt文件只需要带有空格,该程序即可区分,txt文件内容如下{
小羊 65 69 68
小李 94 89 98
}
#include <iostream>
#include <fstream>
using namespace std;
struct Student
{
char name[20];
int s1;
int s2;
int s3;
int average;
};
const int N=2;
int main( )
{
int i, stuNum=0;
Student stu[N];
ifstream infile("haha.txt",ios::in);
if(!infile)
{
cout<<"open error!"<<endl;
return 0;
}
i=0;
while(!infile.eof())
{
infile>>stu[i].name>>stu[i].s1>>stu[i].s2>>stu[i].s3;
stu[i].average=(stu[i].s1+stu[i].s2+stu[i].s3)/3;
++stuNum;
++i;
}
infile.close();
//display
for(i=0; i<stuNum; ++i)
{
cout<<stu[i].name<<endl;
cout<<"三科分别为:"<<stu[i].s1<<" "<<stu[i].s2<<" "<<stu[i].s3<<" "<<endl;
cout<<"平均分:"<<stu[i].average<<endl;
}
return 0;
}