"C ++ Primer" chapter 5th after-school practice expressions 21 to 25

Exercises Section 5.5.1 Exercise 5.21 Modify the program so that it repeats the word find must begin with a capital letter.

#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;
}

The last example of section 5.22 of practice jumps back to begin, in fact, better use of loop to complete the task, rewrite the code, no longer pay attention to the use of the goto statement.

do {
	int sz = get_size();
} while (sz <= 0);

Exercise 5.23 write a program that reads two integers, the output of the first number divided by the second number from the standard input.

#include<iostream>
using namespace std;
int main()
{
	int a, b;
	cin >> a >> b;
	cout << a / b << endl;
	return 0;
}

Exercise 5.24 Modify your program so that when the second number is 0, an exception is thrown. Do not set the catch clause, run the program and really enter 0 for the divisor, and see what happens?

#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;
}

Modify your exercise program 5.25 a question, use the try block to catch the exception. users should catch clause prints a message asking if the input number of new and re-execute the contents of the try block.

#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;
}
Published 276 original articles · won praise 21 · views 40000 +

Guess you like

Origin blog.csdn.net/qq_40758751/article/details/104099705