《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;
}
Focus5679
发布了276 篇原创文章 · 获赞 21 · 访问量 4万+
私信
关注
标签:std,25,main,21,int,5th,using,include,cout 来源: https://blog.csdn.net/qq_40758751/article/details/104099705