ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

《C++ Primer》5th 课后练习 第四章 表达式 21~25

2020-01-28 15:07:05  阅读:280  来源: 互联网

标签:std 25 main 21 int 5th using include cout


练习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;
}
Focus5679 发布了276 篇原创文章 · 获赞 21 · 访问量 4万+ 私信 关注

标签:std,25,main,21,int,5th,using,include,cout
来源: https://blog.csdn.net/qq_40758751/article/details/104099705

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有