標籤:
程式在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;
}
C++入門程式作業2