Template IO Module
This is a single-file, header-only input validation with two variadic output functions. One output function simply inserts a new line char after every output and the other one inserts a space; this is the only difference.
The end goal of this project is a convenient, cross-platform IO module, and I thought that the static type-checking and compile-time generation of templates would be the perfect combination of type safety without run-time overhead, with the added bonus of the simplicity of adding a header-only module to an existing project.
Source
#ifndef _INPUT_VALIDATION_HPP
#define _INPUT_VALIDATION_HPP
/** Required STL Header Files for this module:
* #include <iostream>
* #include <limits>
* #include <typeinfo>
*
*/
namespace IO {
template <typename T>
void print(const T& input)
{
std::cout << input << ' ';
}
template <typename T, typename... Types>
void print(const T& firstArg, const Types&... arguments)
{
std::cout << firstArg << ' ';
print(arguments...);
}
template <typename T>
void println(const T& input)
{
std::cout << input << std::endl;
}
template <typename T, typename... Types>
void println(const T& firstArg, const Types&... arguments)
{
std::cout << firstArg << std::endl;
println(arguments...);
}
template <typename T>
T get()
{
auto IO_status_flag = false;
T response;
std::cin >> response;
do {
if (std::cin.fail()) {
IO::print("[Error] Please enter a valid response:");
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cin >> response;
} else {
IO_status_flag = true;
}
} while (IO_status_flag != true);
return response;
}
}
#endif /* _INPUT_VALIDATION_HPP */
Test Code
#include <iostream>
#include <limits>
#include <typeinfo>
#include "input-validation.hpp"
int main()
{
IO::print("Please enter username:");
auto username = IO::get<std::string>();
IO::print("Please enter age:");
auto age = IO::get<int>();
IO::print("\nName:", username);
IO::print("\nAge:", age);
auto array = { "one", "two", "three", "four", "five", "six" };
IO::println("\n");
for(auto str : array)
{
IO::println(str);
}
}
Output
Please enter username: Jose
Please enter age: 23
Name: Jose
Age: 23
one
two
three
four
five
six