-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsafe_stream_input.cpp
More file actions
51 lines (43 loc) · 1.2 KB
/
Copy pathsafe_stream_input.cpp
File metadata and controls
51 lines (43 loc) · 1.2 KB
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
#include <iostream>
#include <string>
#include <fstream>
#include <limits>
using namespace std;
/* SafeStreamInput() - This function will reset error bits in an
input stream when it fails to perform the conversation asked of
it. For example:
int i;
cin >> i;
If you enter a letter, the conversion to integer will fail.
Until the error bits in cin are reset, uses of cin will fail.
The same is true for End-Of-File (EOF). After an EOF is received,
all uses of the input stream will fail silently.
This function will THROW an exception if one of the error bits
were set. If an EOF is received, the exception will read "eof".
If it was a conversion failure, an appropriate string is returned.
Study main() to see how the exceptions are handled.
*/
void SafeStreamInput(istream & s, bool b) {
if (!b) {
if (s.eof())
throw string("eof");
s.clear();
s.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
throw string("conversion failure");
}
}
int main() {
int i = 0;
while(i != 10) {
try {
cout << "Enter a number: ";
SafeStreamInput(cin, bool(cin >> i));
} catch (string s) {
if (s == "eof")
break;
if (s == "conversion failure")
continue;
}
}
return 0;
}