https://rentry.org/PPP2_p351

// Code derived from Stroustrup's PPP2 book
// § 10.4 Opening a file
//  -and beginning on p 351

#include <fstream>
#include <iomanip>
#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 Point {
  int x;
  int y;

  friend istream& operator>>(istream& ist, Point& p)
  {
    char a, b, c;

    if ((ist >> a >> p.x >> b >> p.y >> c) &&
        ! (a == '(' && b == ',' && c == ')'))
      error("Invalid format");

    return ist;
  }

  friend ostream& operator<<(ostream& ost, const Point& p)
  {
    return ost << '(' << setw(2) << p.x << ',' << setw(2) << p.y << ')';
  }
};

int main()
try {
  cout << "Please enter name of output file: ";
  string oname;
  cin >> oname;

  ofstream ost{oname};  // ost is an output stream for a file named oname
  if (! ost)
    error("can't open output file ", oname);

  vector<Point> points;
  for (int i = 0; i < 10; ++i) {
    Point p = {i, i * i};
    points.push_back(p);
  }

  for (Point& p : points)
    ost << '(' << p.x << ',' << p.y << ")\n";

} catch (exception& e) {
  cerr << "error: " << e.what() << '\n';
  return 1;

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

void fill_from_file(vector<Point>& points, string& name)
{
  ifstream ist{name};  // open file for reading
  if (! ist)
    error("can't open input file ", name);

  // . . . use ist . . .

  for (auto& p : points)  // trivial use
    cout << p << '\n';

  // the ifstream file is implicitly closed here when we leave this function
}

build & run:

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

PrevUpNext

Edit
Pub: 07 Apr 2023 21:56 UTC
Edit: 03 May 2023 09:40 UTC
Views: 304