Based on this question, I wrote my own implementation of the yesno function I suggested. The function reads an answer until it is either "y" or "yes" or "n" or "no" (case-insensitive).
#include <algorithm>
#include <cctype>
#include <cstdlib>
#include <iostream>
#include <string>
bool yesno(const std::string &prompt)
{
while (true) {
std::cout << prompt << " [y/n] ";
std::string line;
if (!std::getline(std::cin, line)) {
std::cerr << "\n";
std::cerr << "error: unexpected end of file\n";
std::exit(EXIT_FAILURE);
}
std::transform(line.begin(), line.end(), line.begin(),
[](unsigned char x){return std::tolower(x);});
if (line == "y" || line == "yes") {
return true;
}
if (line == "n" || line == "no") {
return false;
}
}
}
int main()
{
bool include_digits = yesno("Should the password include digits?");
if (include_digits) {
std::cout << "le1mein\n";
} else {
std::cout << "letmein\n";
}
}
I took care to:
- Include all necessary headers.
- Call the
std::tolowerfunction with anunsigned charas argument. - Use
std::getlineinstead of the hard-to-control>>operator. - Catch all errors (except for writing to
std::cout).
Anything that I missed?
binary_responseclass and overload stream operators. Also I would overload operator bool, so the syntax and semantics would be dope af. Should I write this as answer? \$\endgroup\$