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。