// Code derived from Stroustrup's PPP2 book// § 10.5 Reading and writing a file// -and beginning on p 353#include<fstream>#include<iostream>#include<stdexcept>#include<string>#include<vector>usingnamespacestd;voiderror(conststrings){throwruntime_error(s);}voiderror(conststrings1,conststrings2){error(s1+s2);}//------------------------------------------------------------------------------structReading{// a temperature readinginthour;// hour after midnight [0:23]doubletemp_F;// in Fahrenheit};intmain()try{// open an input disk file stream; ready for reading data in from:cout<<"Please enter input file name (eg, temps.txt ): ";stringiname;cin>>iname;ifstreamist{iname};// ist reads from a file named in the string 'iname'if(!ist)error("can't open input file ",iname);// open an output disk file stream; ready for writing data out to:// -(and creating it beforehand, if necessary)cout<<"Please enter output file name (eg, temps_fmt.txt ): ";stringoname;cin>>oname;if(oname==iname)error("this would overwrite the original file");ofstreamost{oname};// ost writes to a file named in the string 'oname'if(!ost)error("can't open output file ",oname);// we'll store the readings' input data here:inthour;doubletemp;vector<Reading>readings;// now, read and write the two streams:// read raw data from input stream (our input disk file, in this case)while(ist>>hour>>temp){if(hour<0||23<hour)error("hour out of range");readings.push_back(Reading{hour,temp});}// write formatted data to output stream (our output disk file, in this case)for(auto&reading:readings)ost<<'('<<reading.hour<<','<<reading.temp_F<<")\n";}catch(exception&e){cerr<<"error: "<<e.what()<<'\n';return1;}catch(...){cerr<<"Oops: unknown exception!\n";return2;}