《Essential C++》第一章练习
刚看完第一章~做做练习 = = 前4题偷懒不做,从第5题开始……
练习1.5:cstyle的char*和string
-
#include<iostream>
-
#include<cstring>
-
using namespace std;
-
-
int main()
-
{
-
char cname[15];
-
-
cout<<"What's your name? : ";
-
cin>>cname;
-
-
while(strlen(cname)<=2)
-
{
-
cout<<"A name's length must > 2! please input your name again: ";
-
cin>>cname;
-
}
-
-
cout<<"Hello, "<<cname<<" !"<<endl;
-
-
return 0;
-
}
-
#include<iostream>
-
#include<string>
-
using namespace std;
-
-
int main()
-
{
-
string name;
-
-
cout<<"What's your name? : ";
-
cin>>name;
-
-
while(name.size() <= 2)
-
{
-
cout<<"A name's length must > 2! please input your name again: ";
-
cin>>name;
-
}
-
-
cout<<"Hello, "<<name<<" !"<<endl;
-
-
return 0;
-
}
练习1.6:array和vector
-
#include<iostream>
-
using namespace std;
-
-
int main()
-
{
-
const int N = 10;
-
int number[N];
-
-
cout<<"please input "<<N<<" integers: ";
-
-
int i = 0;
-
for(i=0; i<N; i++) cin>>number[i];
-
-
int sum = 0;
-
for(i=0; i<N; i++)
-
{
-
sum += number[i];
-
}
-
cout<<"The sum of these numbers is " << sum << endl;
-
-
cout<<"The average of these numbers is "<< ((double)sum)/N <<endl;
-
-
return 0;
-
}
-
#include<iostream>
-
#include<vector>
-
using namespace std;
-
-
int main()
-
{
-
vector<int> vt;
-
int i;
-
-
cout<<"please input integers: ";
-
while(cin>>i){
-
if(i==-1)break;
-
vt.insert(vt.end(), i);
-
}
-
-
int sum = 0;
-
for(i=0; i<vt.size(); i++)
-
sum += vt[i];
-
cout<<"The sum of these integers is " << sum << "." << endl;
-
-
cout<<"The average of these integers is "<< ((double)sum/vt.size()) <<". "<< endl;
-
-
return 0;
-
}
练习1.7:偷懒 没有做到每个字读,只做了每行读
-
#include<iostream>
-
#include<fstream>
-
#include<algorithm>
-
#include<string>
-
#include<vector>
-
using namespace std;
-
-
int main()
-
{
-
vector<string> content;
-
ifstream infile("ex_1_7_in.txt", ios_base::in);
-
ofstream outfile("ex_1_7_out.txt");
-
-
if(!infile)
-
{
-
cout<<"File Cannot Open!"<<endl;
-
}
-
else
-
{
-
string line;
-
-
while(infile>>line)content.push_back(line+'\n');
-
-
vector<string>::iterator iter;
-
for(iter = content.begin();iter!=content.end(); ++iter)
-
{
-
cout<<(*iter);
-
}
-
-
sort(content.begin(), content.end());
-
-
for(iter = content.begin();iter!=content.end(); ++iter)
-
{
-
outfile<<(*iter);
-
}
-
}
-
-
return 0;
-
}
练习1.8:偷懒,让用户自己输入错误次数 囧
-
#include<iostream>
-
#include<string>
-
using namespace std;
-
-
int main()
-
{
-
string msg[4] = {"You are great!", "Good job!", "25%", "0%"} ;
-
-
int user_wrong_value;
-
-
cout<<"How many the user wrongs..?(<4): ";
-
cin>>user_wrong_value;
-
-
cout<<msg[user_wrong_value]<<endl;
-
-
return 0;
-
}
2009年11月28日 05:37
好好向你学习才是