// Code derived from Stroustrup's PPP2 book// § 10.10 A standard input loop// -and beginning on p 366#include<iostream>#include<stdexcept>#include<string>usingnamespacestd;voiderror(conststrings){throwruntime_error(s);}voiderror(conststrings1,conststrings2){error(s1+s2);}//------------------------------------------------------------------------------typedefintMy_type;voidend_of_loop(istream&ist,charterm,conststring&message){if(ist.fail()){// use term as terminator and/or separatorist.clear();charch;if(ist>>ch&&ch==term)return;// all is fineerror(message);}}voidinput_loop_v1(istream&ist){for(My_typevar;ist>>var;){// read until end of file// maybe check that var is valid// . . . do something with var . . .}// we can rarely recover from bad; don’t try unless you really have to:if(ist.bad())error("bad input stream");if(ist.fail()){// was it an acceptable terminator?}// carry on: we found end of file}voidinput_loop_v2(istream&ist){for(My_typevar;ist>>var;){// read until end of file// maybe check that var is valid// . . . do something with var . . .}if(ist.fail()){// use '|' as terminator and/or separatorist.clear();charch;if(!(ist>>ch&&ch=='|'))error("bad termination of input");}// carry on: we found end of file or a terminator}voidinput_loop_v3(istream&ist){for(My_typevar;ist>>var;){// read until end of file// maybe check that var is valid// . . . do something with var . . .}end_of_loop(ist,'|',"bad termination of file");// test if we can continue// carry on: we found end of file or a terminator}intmain()try{istream&ist{cin};// make ist throw if it goes bad (so we no longer need to test for that state)ist.exceptions(ist.exceptions()|ios_base::badbit);input_loop_v1(ist);input_loop_v2(ist);input_loop_v3(ist);// <- this version would be our 'standard loop' choice}catch(exception&e){cerr<<"error: "<<e.what()<<'\n';return1;}catch(...){cerr<<"Oops: unknown exception!\n";return2;}