ClientServerProject/libraries/user_input.h

60 lines
1.9 KiB
C
Raw Normal View History

2021-02-09 23:02:05 -05:00
#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, decltype(lb) ub> [[maybe_unused]]
constexpr auto is_between(decltype(lb) x) -> bool { return (ub > x) && (x > lb); }
2021-02-11 02:40:29 -05:00
template<auto lb> [[maybe_unused]]
constexpr auto is_larger(decltype(lb) x) -> bool { return (x > lb); }
2021-02-11 02:40:29 -05:00
template<auto ub> [[maybe_unused]]
constexpr auto is_smaller(decltype(ub) x) -> bool { return (ub > x); }
2021-02-11 02:40:29 -05:00
template<typename T> [[maybe_unused]]
2021-02-10 16:32:59 -05:00
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];
}
2021-02-09 23:02:05 -05:00
}
2021-02-12 03:19:18 -05:00
struct ip_validator { bool operator()(const std::string& addr) const { return net::getaddrinfo(addr, "0") != nullptr; }};
2021-02-11 02:40:29 -05:00
template<typename T> [[maybe_unused]]
2021-02-09 23:02:05 -05:00
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...*/
}
2021-02-10 16:32:59 -05:00
struct always_true_validator { template<typename T> bool operator()(T) const { return true; }};
2021-02-11 02:40:29 -05:00
template<typename T> [[maybe_unused]]
2021-02-10 16:32:59 -05:00
T get_input(const std::string& prompt) { return get_input<T>(prompt, "", always_true_validator()); }