rafb-getint.cpp

(plain text)
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
#include <iostream>
#include <string>
#include <limits>

/***
 * If the given istream failed due to bad input, reset it to a good state;
 * in any case, ignores the rest of the current line (including any bad input).
 ***/
std::istream &flush (std::istream &in) {
  if (in.rdstate() == in.failbit) in.clear();
  return in.ignore(std::numeric_limits<int>::max(), '\n');
}

int main () {
  using namespace std;

  int i;

  bool valid = false;
  while (cin && !valid) {
    cout << "Enter an integer between 6 and 31 (inclusive): ";
    if (cin >> i && (6 <= i && i <= 31)) valid = true;
    flush(cin);
  }

  string s;

  valid = false;
  while (cin && !valid) {
    cout << "Enter a string of more than 15 letters: ";
    if (getline(cin, s) && s.size() > 15) valid = true;
  }

  cout << "Your number was " << i << "\n";
  cout << "Your string was " << s << "\n";

  return 0;
}