https://rentry.org/PPP2_p145

// Code derived from Stroustrup's PPP2 book
// § 5.5.3 Error reporting
//  -and beginning on p 145

#include <iostream>
#include <string>

using std::cin;
using std::cout;
using std::string;

// ask user for a yes-or-no answer;
// return 'b' to indicate a bad answer (i.e., not yes or no)
char ask_user(string question)
{
  cout << question << "? (yes or no)\n";
  string answer = " ";
  cin >> answer;

  if (answer == "y" || answer == "yes")
    return 'y';

  if (answer == "n" || answer == "no")
    return 'n';

  return 'b';  // ‘b’ for “bad answer”
}

// calculate area of a rectangle;
// return –1 to indicate a bad argument
int area(int length, int width)
{
  if (length <= 0 || width <= 0)
    return -1;

  return length * width;
}

int main()
{
  const string question = "Are all x of y?";
  char         answer   = ask_user(question);

  //---

  int y = 0;  // please test out some positive values here, too
  int z = 0;  //

  int area1 = area(y, z);

  //---

  cout << answer << '\n'  //
       << y << '\n'       //
       << z << '\n'       //
       << area1 << '\n';
}

build & run:

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

PrevUpNext

Edit
Pub: 22 Feb 2023 04:32 UTC
Edit: 29 Apr 2023 09:16 UTC
Views: 386