https://rentry.org/PPP2_p357

// Code derived from Stroustrup's PPP2 book
// § 10.6 I/O error handling
//  -and beginning on p 357

#include <iostream>
#include <stdexcept>
#include <vector>

using namespace std;

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

// read integers from ist into v until we reach eof() or terminator
void fill_vector(istream& ist, vector<int>& v, char terminator)
{
  for (int i; ist >> i;)
    v.push_back(i);

  if (ist.eof())
    return;  // fine: we found the end of file

  // not good() and not bad() and not eof(); so ist must be fail() :

  ist.clear();  // clear stream state

  char c;
  ist >> c;                        // read a character, hopefully terminator
  if (c != terminator) {           // ouch: not the terminator, so we must fail
    ist.unget();                   // maybe my caller can use that character
    ist.clear(ios_base::failbit);  // set the state to fail()
  }
}

int main()
try {
  istream& ist{cin};

  // makes ist throw if it goes bad
  ist.exceptions(ist.exceptions() | ios_base::badbit);

  vector<int> v;
  fill_vector(ist, v, '*');

} 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_p357.cpp && ./a.out

PrevUpNext

Edit
Pub: 07 Apr 2023 22:08 UTC
Edit: 03 May 2023 09:53 UTC
Views: 390