C++入門程式作業2

來源:互聯網
上載者:User

標籤:

程式在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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.