《C++ Primer》5th 课后练习 第五章 语句 21~25

练习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;
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值