A more proper version of this utility can be found at the following link here: Giveth me thy easier user input in C++ - follow upGiveth me thy easier user input in C++ - follow up.
I've always been a little bothered by the fact, that in order to get user input in C++, one had to use up to three lines of code in an ugly manner like the below to get user input for a specific type, with a prompt:
int user_input; std::cout << ">> "; std::cin << user_input;
So, in order to make this process easier, I've created an easy_input function which allows for the user to specify a type, a prompt, and set user input to a variable, all in one line.
easy_input.h
#ifndef EASY_INPUT_H_
#define EASY_INPUT_H_
#pragma once
#include <iostream>
#include <string>
// We're simply "re-defining" the standard namespace
// here so we can patch our easy_input function into
// it for the user's sake.
namespace std
{
template <typename TInput>
TInput easy_input(const std::string& prompt);
}
/**
* This function serves as a wrapper for obtaining
* user input. Instead of writing three lines every
* time the user wants to get input, they can just
* write one line.
* @param {any} TInput - The type of the input.
* @param {string} prompt - The prompt to use for input.
* @returns - Whatever the user entered.
*/
template <typename TInput>
TInput std::easy_input(const std::string& prompt)
{
TInput user_input_value;
std::cout << prompt;
std::cin >> user_input_value;
return user_input_value;
}
#endif
main.cpp (tests)
#include <iostream>
#include <string>
#include "easy_input.h"
int main()
{
const std::string user_input1 = std::easy_input<std::string>(">> ");
std::cout << user_input1 << "\n";
const int user_input2 = std::easy_input<int>(">> ");
const int user_input3 = std::easy_input<int>(">> ");
std::cout << user_input2 + user_input3 << "\n";
}
I'd (preferably) like to know the following things:
- Am I using templates appropriately? I feel like I might have done something wrong here in the process.
- Is there anything that can be improved performance-wise?
- Is there a need for include guards?
- Is it okay to patch
easy_inputintostdwithout problems? Is this a good practice? - Is there anything else that's glaringly wrong?