https://rentry.org/PPP2_p353

// 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>

using namespace std;

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

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

struct Reading {  // a temperature reading
  int    hour;    // hour after midnight [0:23]
  double temp_F;  // in Fahrenheit
};

int main()
try {
  // open an input disk file stream; ready for reading data in from:

  cout << "Please enter input file name (eg, temps.txt ):  ";
  string iname;
  cin >> iname;

  ifstream ist{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 ):  ";
  string oname;
  cin >> oname;
  if (oname == iname)
    error("this would overwrite the original file");

  ofstream ost{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:

  int             hour;
  double          temp;
  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';
  return 1;

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

build & run:

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

PrevUpNext

Edit
Pub: 07 Apr 2023 22:01 UTC
Edit: 03 May 2023 09:45 UTC
Views: 514