https://rentry.org/PPP2_p394

// Code derived from Stroustrup's PPP2 book
// § 11.4 String streams
//  -and beginning on p 394

#include <fstream>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <string>

using namespace std;

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

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

// if possible, convert characters in s to floating-point value
double str_to_double(string s)
{
  istringstream is{s};  // make a stream so we can read from s

  double d;
  is >> d;
  if (! is)
    error("double format error: ", s);

  return d;
}

void test()
try {
  [[maybe_unused]] double d1 = str_to_double("12.4");
  [[maybe_unused]] double d2 = str_to_double("1.234568e+03");
  [[maybe_unused]] double d3 = str_to_double("twelve point three");  // error:

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

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

struct Temperature {
  double temp;
  string unit;
};

void my_code(string label, Temperature temp)
{
  // . . .

  ostringstream os;  // stream for composing a message
  os << setw(8) << label << ": " << fixed << setprecision(5) << temp.temp
     << temp.unit;

  // exposition only:
  // someobject.display(Point(100, 100), os.str().c_str());

  // . . .
}

// get the next incremental number for a log file
int get_next_number()
{
  static int n{0};
  return ++n;
}

int main()
try {
  test();

  int seq_no = get_next_number();  // get the number of a log file

  ostringstream name;
  name << "myfile" << seq_no << ".log";  // e.g., myfile17.log
  ofstream logfile{name.str()};          // e.g., open myfile17.log

} catch (exception const& 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_11/main_p394.cpp && ./a.out

PrevUpNext

Edit
Pub: 09 Apr 2023 05:55 UTC
Edit: 03 May 2023 10:32 UTC
Views: 563