練習5.21 修改5.5.1節練習題的程序,使其找到的重複單詞必須以大寫字母開頭。
#include<iostream>
#include<string>
#include<vector>
using namespace std;
int main()
{
string s, pres="";
bool flag = true;
while (cin >> s) {
if (s == pres) {
flag = false;
if (isupper(s[0]))
break;
else
continue;
}
pres = s;
}
if(flag)
cout << "no word was repeated." << endl;
else {
cout << s << " occurs twice in succession." << endl;
}
return 0;
}
練習5.22 本節的最後一個例子跳回到 begin,其實使用循環能更好的完成該任務,重寫這段代碼,注意不再使用goto語句。
do {
int sz = get_size();
} while (sz <= 0);
練習5.23 編寫一段程序,從標準輸入讀取兩個整數,輸出第一個數除以第二個數的結果。
#include<iostream>
using namespace std;
int main()
{
int a, b;
cin >> a >> b;
cout << a / b << endl;
return 0;
}
練習5.24 修改你的程序,使得當第二個數是0時拋出異常。先不要設定catch子句,運行程序並真的爲除數輸入0,看看會發生什麼?
#include<iostream>
using namespace std;
int main()
{
int a, b;
cin >> a >> b;
if (b == 0)
throw runtime_error("divisor is zero");
cout << a / b << endl;
return 0;
}
練習5.25 修改上一題的程序,使用try語句塊去捕獲異常。catch子句應該爲用戶輸出一條提示信息,詢問其是否輸入新數並重新執行try語句塊的內容。
#include<iostream>
#include<string>
using namespace std;
int main()
{
int a, b;
string s;
while (true) {
cout << "please input tow numbers: " << endl;
cin >> a >> b;
try {
if (b == 0)
throw runtime_error("divide is not zero");
cout << a / b << endl;
}
catch (runtime_error err) {
cout << err.what() << "\nTry agsin? Enter yes or no" << endl;
cin >> s;
if (!s.empty() && s[0] == 'n')
break;
}
}
return 0;
}