https://rentry.org/PPP2_p350

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

#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 input file name (eg, points.txt ):  ";
  string iname;
  cin >> iname;

  ifstream ist{iname};  // ist is an input stream for the file named in iname
  if (! ist)
    error("can't open input file ", iname);

  vector<Point> points;
  for (Point p; ist >> p;)
    points.push_back(p);

  for (auto& p : points)
    cout << p << '\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_p350.cpp && ./a.out

UpNext

Edit
Pub: 07 Apr 2023 21:43 UTC
Edit: 03 May 2023 09:38 UTC
Views: 317