// 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>usingnamespacestd;voiderror(conststrings){throwruntime_error(s);}voiderror(conststrings1,conststrings2){error(s1+s2);}//------------------------------------------------------------------------------intmain()try{cout<<"Please enter an integer in the range 1 to 10 (inclusive):\n";intn=0;while(true){cin>>n;if(cin){// we got an integer; now check itif(1<=n&&n<=10)break;cout<<"Sorry "<<n<<" is not in the [1:10] range; please try again\n";}elseif(cin.fail()){// we found something that wasn’t an integercin.clear();// set the state back to good();// -we want to look at the characterscout<<"Sorry, that was not a number; please try again\n";for(charch;cin>>ch&&!isdigit(ch);){// throw away non-digits;// do nothing (AKA 'nop' )}if(!cin)error("no input");// we didn’t find a digit: give upcin.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';return1;}catch(...){cerr<<"Oops: unknown exception!\n";return2;}