https://rentry.org/PPP2_p361

// Code derived from Stroustrup's PPP2 book
// § 10.7.1 Breaking the problem into manageable parts
//  -and beginning on p 361

#include <cctype>
#include <iostream>
#include <stdexcept>
#include <string>

using namespace std;

void error(const string s) { throw runtime_error(s); }
void error(const string s1, const string s2) { error(s1 + s2); }

//------------------------------------------------------------------------------

void skip_to_int()
{
  if (cin.fail()) {  // we found something that wasn’t an integer
    cin.clear();     // we’d like to look at the characters

    for (char ch; cin >> ch;) {  // throw away non-digits
      if (isdigit(ch) || ch == '-') {
        cin.unget();  // put the digit back, so that we can read the number
        return;
      }
    }
  }

  error("no input");  // eof or bad; give up
}

// read an int from cin
int get_int()
{
  int n = 0;

  while (true) {
    if (cin >> n)
      return n;

    cout << "Sorry, that was not a number; please try again\n";

    skip_to_int();
  }
}

// read an int in [low:high] from cin
// the range-checking get_int()
int get_int(int low, int high)
{
  cout << "Please enter an integer in the range " << low << " to " << high
       << " (inclusive):\n";

  while (true) {
    int n = get_int();

    if (low <= n && n <= high)
      return n;

    cout << "Sorry " << n << " is not in the [" << low << ':' << high
         << "] range; please try again\n";
  }
}

int main()
try {
  int n = get_int(1, 10);
  cout << "n: " << n << '\n';

  int m = get_int(2, 300);
  cout << "m: " << m << '\n';

} catch (exception& e) {
  cerr << "error: " << e.what() << '\n';
  return 1;

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

build & run:

g++ -std=c++20 -O2 -Wall -pedantic ./ch_10/main_p361.cpp && ./a.out

PrevUpNext

Edit
Pub: 07 Apr 2023 22:23 UTC
Edit: 03 May 2023 10:03 UTC
Views: 370