5.1 簡單語句
1、空語句
; //只有一個分號
2、if語句
(1)格式:
if(condition)
statement1;
else if(condition2)
statement2;
....
....
else
statement3;
5.3.1節練習
5.5:寫一段程序,使用if else語句實現把數字成績轉換成字幕成績的要求。
int grade;
char c;
cin>>grade;
if(grade<50)
c='D';
else if(grade>50&&grade<60)
c='C';
else if(grade>60&&grade<80)
c='B';
else
c='A';
cout<<"grade="<<c<<endl;
5.6:改寫5.5的程序,使用條件運算符代替if else語句。
int grade;
cin>>grade;
cout<<"grade="<<(grade<50?'D':(grade>50||grade<60?'C':(grade>60||grade<80?'B':'A')))<<endl;
3、switch語句
(1)格式:
switch()
{
case expr1:
statement1;
(break;)
case expr2:
statement;
(break;)
....
....
default:
statement;
(break;)
}
5.3.2 節練習
練習5.9 :編寫一段程序,使用一系列if語句統計從cin讀入的文本中有多少元音字符
char c;
int count=0;
std::vector<char> vc;
while(cin>>c&&c!='#')
vc.push_back(c);
for(auto k:vc)
{
if(k=='a'||k=='A')
++count;
else if(k=='e'||k=='E')
++count;
else if(k=='i'||k=='I')
++count;
else if(k=='o'||k=='O')
++count;
else if(k=='u'||k=='U')
++count;
else
continue;
}
cout<<"Yuanyin zimu:"<<count<<endl;
練習5.10:編寫一段程序,既統計元音字母的小寫形式,也統計大寫形式。
int count=0;
char c;
std::vector<char> vc;
while(cin>>c&&c!='#')
vc.push_back(c);
for(auto dei:vc)
{
switch(dei)
{
case 'a':++count;break;
case 'A':++count;break;
case 'e':++count;break;
case 'E':++count;break;
case 'i':++count;break;
case 'I':++count;break;
case 'o':++count;break;
case 'O':++count;break;
case 'u':++count;break;
case 'U':++count;break;
default:continue;
}
}
cout<<"yuanyinzimu: "<<count<<endl;
練習5.11:修改統計原因字母的程序,使其也能統計空格、製表和換行符的數量
int count=0;
char c;
std::vector<char> vc;
while(cin.get(c)&&c!='#')
vc.push_back(c);
for(auto dei:vc)
{
if(isspace(dei)||dei==' ')
++count;
switch(dei)
{
case 'a':++count;break;
case 'A':++count;break;
case 'e':++count;break;
case 'E':++count;break;
case 'i':++count;break;
case 'I':++count;break;
case 'o':++count;break;
case 'O':++count;break;
case 'u':++count;break;
case 'U':++count;break;
default:continue;
}
}
cout<<"yuanyinzimu: "<<count<<endl;
4、迭代語句(循環)
(1)while語句
<1>格式:
while(condition) //條件爲真,則執行下面的語句;
statement;
5.4.1 節練習
5.14:編寫一段程序,從標準輸入中讀取若干string對象並查看連續重複出現的單詞,要求記錄練習重複出現的最大次數以及對應的單詞。如果這樣的單詞存在,輸出重複出現的最大次數,如果不存在,輸出一條信息說明任何單詞都沒有連續出現過
string a;
int count=1;
int tmp=0;
std::vector<int> iv;
std::vector<string> vstr;
while(cin>>a&&a!="quit")
vstr.push_back(a);
for (std::vector<string>::iterator is = vstr.begin();
is != vstr.end();
++is)
{
if(is==vstr.end()-1)
break;
if(*is==*(is+1))
{
cout<<*is<<endl;
count+=1;
cout<<count<<endl;
iv.push_back(count);
}
else
count=1;
}
for(auto i=iv.begin();i!=iv.end();++i)
{
if(i==iv.end()-1)
break;
cout<<*i<<endl;
if(*i<*(i+1))
tmp=*(i+1);
else
tmp=*i;
}
if(iv.empty())
cout<<"No same words.\n";
else
cout<<"The words "<<a<<" show up "<<tmp<<" times."<<endl;
(2)傳統for語句
<1>格式:
for(init-statement;condition;expression)
statement;
<2>init-statement 可有多個,但condition只能有一個,expression可有多個。
5.4.2 節練習
練習5.17:編寫一段程序,檢驗其中一個vector對象是否是另一個的前綴。
std::vector<int> iv1;
int i1;
std::vector<int> iv2;
int i2;
cout<<"Enter the element of iv1: "<<endl;
while(cin>>i1&&i1!=9)
iv1.push_back(i1);
cout<<"Enter the element of iv2: "<<endl;
while(cin>>i2&&i2!=9)
iv2.push_back(i2);
if(iv1.size()<iv2.size())
for(auto itv1=iv1.begin(),itv2=iv2.begin();itv1!=iv1.end();++itv1,++itv2)
if(*itv1!=*itv2)
cout<<"itv1 is not the qianzhui."<<endl;
else
cout<<"itv1 is the qianzhui."<<endl;
else
for(auto itv1=iv1.begin(),itv2=iv2.begin();itv2!=iv2.end();++itv1,++itv2)
if(*itv1!=*itv2)
cout<<"itv2 is not the qianzhui."<<endl;
else
cout<<"itv2 is the qianzhui."<<endl;
(3)範圍for語句(range for):
<1>格式:
for(declaration:expression)
statement;
<2>作用:能遍歷容器或其他序列的所有元素。
5、do…while語句
(1)格式:
do
statement;
while(condition);
5.4.4 練習
練習5.19:編寫一段程序,使用do…while循環重複第執行下述任務;首先提示用戶輸入兩個string對象,然後挑出比較短的那個並輸出它
do
{
int v1,v2;
cout<<"Please enter two numbers to sum: ";
if(cin>>v1>>v2)
cout<<"Sum is: "<<v1+v2<<endl;
}
while(cin);
5.5
跳轉語句
1、break語句:負責終止離它最近的while、do、do…while、for或switch語句,並從這些語句之後的第一條語句開始繼續執行
2、continue語句:終止最近的循環迭代並立即開始下一次迭代。continue語句只出現在for、while和do…while循環內部
3、goto語句:無條件跳轉到同一函數內的另一條語句。(儘量不用,容易引起程序流的混亂)
5.5.1 節練習
練習5.20:編寫一段程序,從標準輸入中讀取string對象的序列直到連續重複出現兩個相同的單詞或者所有單詞都讀完爲止。
string str1,str2;
do
{
cout<<"Enter string1: "<<endl;
getline(cin,str1);
cout<<"Enter string2: "<<endl;
getline(cin,str2);
if(str1.size()<str2.size())
cout<<"The shortest string: "<<str1<<endl;
else
cout<<"The shortest string: "<<str2<<endl;
}
while(str1=="quit"||str2=="quit");
練習5.21:修改5.5.1節練習題的程序,使其找到的重複單詞必須以大寫字母開頭:
string str1;
string str2;
do
{
cout<<"Enter the word: "<<endl;
cin>>str1;
auto c1=str1.begin(),c2=str2.begin();
if(isupper(*c1)&&isupper(*c2)&&str1==str2)
{
cout<<str1<<" and "<<str2<<" are same word"<<endl;
break;
}
else
cout<<"Not the same word."<<endl;
str2=str1;
}
while(1);
5.6 try語句塊和異常處理
1、C++語言中異常處理包括一下三個部分
(1)throw表達式(throw expression),異常檢測使用throw表達式來表示它遇到了無法處理的問題,我們說throw 引發(raise) 了異常。
(2)try語句塊(try bolck),異常處理部分使用try語句塊處理異常。try語句塊以關鍵字 try 開始,並以一個或多個catch子句(catch clause)結束。
<1>try語句塊中代碼拋出的異常通常會被某個catch子句處理。因爲catch子句“處理”異常,所以稱作異常處理代碼(exception handler)
(3)一套異常類(exception class),用於在throw表達式和相關的catch子句之間傳遞異常的具體信息。
5.6.1 throw表達式
1、throw表達式包含關鍵字throw和緊隨其後的一個表達式,表達式的類型爲拋出異常類型。
2、例:
if(item1.isbn()!=item2.isbn())
throw runtime_error("Data must refer to same IBSN");
cout<<item+item2<<endl;
(1)如果ISBN不一樣就拋出一個異常,異常類型爲runtime_error的對象。拋出的異常將終止當前的函數,並把控制權轉移給處理該異常的代碼。
(2)runtime_error是標準庫異常類型的一種,定義在stdexcept頭文件中。
5.6.2 try語句塊
1、語法格式:
try{
program-statements
}catch(exception-declaration){
handler-statements;
}catch(exception-declaration){
handler-statements;
}
....
(1)program-statements爲try語句塊內的語句。
(2)exception-declaration爲異常的聲明
(3)handler-statements爲處理異常的語句
2、異常終端了程序的正常流程。
5.6.3 標準異常
1、定義的異常類
(1)exception:最常見的問題
(2)runtime_error:只有在運行時才能檢測出的問題
(3)range_error:運行時錯誤:生成的結果超出了有意義的值域範圍
(4)overflow_error:運行時錯誤:計算上溢
(5)underflow_error:運行時錯誤:計算下溢
(6)logic_error:程序邏輯錯誤
(7)domain_error:邏輯錯誤,參數對應的結果不存在
(8)invalid_argument:邏輯錯誤,參數無效
(9)length_error:邏輯錯誤,視圖創建一個超出該類型最大長度的對象
(10)out_of_range:邏輯錯誤,使用一個超出有範圍的值
2、標準異常類有what成員,返回const char *,是異常的文本信息。
5.6.3 節練習
練習5.23:編寫一段程序,從標準輸入讀取兩個整數,輸出第一個數除以第二個數的結果:
int a,b;
cout<<"Enter to numbers: (/)"<<endl;
while(cin>>a>>b)
{
cout<<"result="<<a/b<<endl;
cout<<"Enter to numbers: (/)"<<endl;
}
練習5.24:修改5.23練習,使得當第二個數是0時拋出異常。先不設定catch子句,運行程序併爲除數輸入0。
int a,b;
cout<<"Enter to numbers: (a/b)"<<endl;
while(cin>>a>>b)
{
if(b==0)
throw runtime_error("b must not equal to 0!\n");
cout<<"result="<<a/b<<endl;
cout<<"Enter to numbers: (/)"<<endl;
}
練習5.25:修改5.24程序,使用try語句塊去捕獲異常。catch子句應該爲用戶輸出一條提示信息,詢問其是否輸入新數並重新執行try語句塊的內容
int a,b;
cout<<"Enter to numbers: (a/b)"<<endl;
while(cin>>a>>b)
{
try
{
if(b==0)
throw runtime_error("b must not equal to 0!\n");
} catch(runtime_error err){
cout<<err.what()
<<"\nTry to enter Again?Enter y or n"<<endl;
char c;
cin>>c;
if(!cin||c=='n')
break;
}
cout<<"result="<<a/b<<endl;
cout<<"Enter to numbers: (a/b)"<<endl;
}
術語表總結
1、異常聲明(exception declaration):位於catch子句中的聲明,指定了該catch子句能處理的異常類型。
2、異常安全(exception safe):當異常拋出後,程序能執行的正確行爲。
3、terminate是一個標準庫函數,當異常沒有被catch到時調用。terminate終止當前程序執行。
4、throw表達式(throw expression):一種中斷當前執行路徑的表達式。throw表達式拋出的一個異常並把控制權轉義到能處理該異常的最近的catch子句。
5、try語句塊(try block):跟在try關鍵字後面的塊,以及一個或多個catch子句。如果try語句塊的代碼引發異常並且其中一個catch子句匹配該異常類型,則異常被該catch子句處理。否則,異常將由外圍try語句塊,或者程序終止。