C++ Primer 第五版 5.51节&5.6.3节练习

5.20

#include <iostream>  
#include <string>
#include <vector>
using namespace std;


int main()
{	
	string words;
	string test = "";
	bool flag = true;
	while (cin>>words&&!words.empty())
	{
		test = words;
		cin >> words;
		if (words == test)
		{
			cout << "连续出现的是:" << words << endl;
			flag = false;
			break;
		}
		
	}
	if (flag)
		cout << "没有任何单词是连续的!" << endl;
	system("pause");
	return 0;
}
5.21

#include <iostream>  
#include <string>
#include <vector>
using namespace std;


int main()
{	
	string words;
	string test = "";
	bool flag = true;
	while (cin>>words&&!words.empty())
	{
		test = words;
		cin >> words;
		if (words == test)
		{
			if (isupper(words[0]) && isupper(test[0]))
			{
				cout << "连续出现且首字母大写的是:" << words << endl;
				flag = false;
				break;
			}
			else 
			{
				cout << "连续出现但首字母没有大写的是:" << words << endl;
				flag = false;
				break;
			}
		}
		
	}
	if (flag)
		cout << "没有任何单词是连续的!" << endl;
	system("pause");

	return 0;
}

5.23

对于try和catch语句块来对异常进行处理

#include <iostream>  
#include <string>
#include <vector>
using namespace std;


int main()
{	
	double a, b,result;
	while (cin >> a >> b)
	{
		
		try
		{
			
			if (b == 0)
				throw runtime_error("b≠0");
			result = a / b;
			cout << result << endl;
			
		}
		catch (runtime_error err)
		{
			cout << err.what() << "\nTry agin? Enter y or n" << endl;
			char c;
			cin >> c;
			if (!cin || c == 'n')
				break;
		}
		
	}
	system("pause");

	return 0;
}

如果我们没有try catch语句来对异常进行处理,只单独抛出异常。那么程序将会告诉我们有哪种异常发生并不会去处理他。就这个例子而言,只会报告发现异常,也就是除数为0。




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值