ClientServerProject/libraries/user_input.h

58 lines
1.8 KiB
C++
Executable File

#pragma once
#include <iostream>
#include <limits>
#include <ostream>
#include <string>
#include <functional>
constexpr auto all = std::numeric_limits<std::streamsize>::max();
namespace math
{
template<auto lb, typeof(lb) ub> [[maybe_unused]]
constexpr auto is_between(typeof(lb) x) -> bool { return (ub > x) && (x > lb); }
template<auto lb> [[maybe_unused]]
constexpr auto is_larger(typeof(lb) x) -> bool { return (x > lb); }
template<auto ub> [[maybe_unused]]
constexpr auto is_smaller(typeof(ub) x) -> bool { return (ub > x); }
template<typename T> [[maybe_unused]]
auto numerical_suffix(T value) -> std::string
{
std::string suffixes[4] = {"th", "st", "nd", "rd"};
value %= 100;
if (math::is_between<11,13>(value))
return "th";
value %= 10;
if (math::is_larger<3>(value))
return "th";
return suffixes[value % 4];
}
}
template<typename T> [[maybe_unused]]
T get_input(const std::string& prompt, const std::string& on_error, std::function<bool(T)> validator) noexcept
{
T user_input{};
try
{
while (true)
{
printf("%s", prompt.c_str());
std::cin >> user_input;
if (std::cin.fail() || !validator(user_input))
{
std::cout << on_error << std::endl;
std::cin.clear();
std::cin.ignore(all, '\n');
continue;
}
break;
}
return user_input;
}
catch (std::exception&) { return user_input; } /* This should not happen ..... cin/cout are not configured to throw...*/
}
struct always_true_validator { template<typename T> bool operator()(T) const { return true; }};
template<typename T> [[maybe_unused]]
T get_input(const std::string& prompt) { return get_input<T>(prompt, "", always_true_validator()); }