range error question

try to using range error to reject non-numbers as input

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57

#include "std_lib_facilities_4.h"

const int amendments_count = 27;

int main()
{
	vector <string> answers(26)
		for (int i = 0;i < answers.size();++i)answers[i] = i);
		for (int i = 0; i <= 27;++1);
		cout << "answers[" << i << "]==" << answers[i] << endl;
	{
		"Amendment 1: Freedom of speech, the press, to form militias, of religion, and of the right to assemble.",
		"Amendment 2: The right to bear arms and form militias.",
		...
                "Amendment 27: ...
	};


	cout << "Which amendment?";
	int amendment_number;

	while (cin >> amendment_number)
	{
		try
		{

			if (amendment_number < 1 || amendment_number >27)
			{
				error("That is not a valid input. Please enter a number betweet 1 and 27.");
			}
			else
			{
				cout << answers[amendment_number - 1] << endl;
			}

			cout << "which amendment?";
		}

		catch (out_of_range&)
		{
			cerr << "Oops! Range error\n";
			keep_window_open();
			return 1;
		}

		catch (...)
		{
			cerr << "Oops: Unknown exception!\n";
			keep_window_open();
			return 2;
		}

		return 0;
	
}
 
I don't really understand about your question but you an reject non number input with isdigit() from <cctype>
http://www.cplusplus.com/reference/cctype/isdigit/?kw=isdigit
If you use the at function instead of the subscript operator [] it will automatically throw an out_of_range exception when the index is out of bounds. Then you don't need to do the range checking yourself. Instead the range checking is be done inside the at function. If it throws an exception you will handle it in the catch block.

http://www.cplusplus.com/reference/vector/vector/at/
Last edited on
Topic archived. No new replies allowed.