https://rentry.org/PPP2_p356

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

#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); }

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

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

  if (ist.bad())
    error("ist is bad");  // stream corrupted; let’s get out of here!

  if (ist.fail()) {  // clean up the mess as best we can and report the problem
    ist.clear();     // clear stream state, so that we can look for terminator

    char c;
    ist >> c;                        // read a character, hopefully a terminator
    if (c != terminator) {           // unexpected character
      ist.unget();                   // put that character back
      ist.clear(ios_base::failbit);  // set the state to fail()
    }
  }
}

int main()
try {
  vector<int> v;

  fill_vector(cin, 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_p356.cpp && ./a.out

PrevUpNext

Edit
Pub: 07 Apr 2023 22:06 UTC
Edit: 03 May 2023 09:50 UTC
Views: 565