https://rentry.org/PPP2_p359

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

#include <iostream>
#include <locale>
#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); }

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

int main()
try {
  cout << "Please enter an integer in the range 1 to 10 (inclusive):\n";
  int n = 0;

  while (true) {
    cin >> n;

    if (cin) {  // we got an integer; now check it
      if (1 <= n && n <= 10)
        break;

      cout << "Sorry " << n
           << " is not in the [1:10] range; please try again\n";

    } else if (cin.fail()) {  // we found something that wasn’t an integer

      cin.clear();  // set the state back to good();
                    // -we want to look at the characters

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

      for (char ch; cin >> ch && ! isdigit(ch);) {  // throw away non-digits
        ;                                           // do nothing (AKA 'nop' )
      }

      if (! cin)
        error("no input");  // we didn’t find a digit: give up

      cin.unget();  // put the digit back, so that we can read the number

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

  // if we get here n is in [1:10]

} 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_p359.cpp && ./a.out

PrevUpNext

Edit
Pub: 07 Apr 2023 22:18 UTC
Edit: 03 May 2023 09:59 UTC
Views: 557