1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
|
#include <iostream>
#include <limits>
#include <string>
using namespace std;
//======================================================================
template <typename T> T getValue( string prompt, T minVal = numeric_limits<T>::min, T maxVal = numeric_limits<T>::max )
{
T value;
cout << prompt;
cin >> value;
if ( !cin ) // Unable to accept input
{
cin.clear();
cin.ignore( 1000, '\n' ); // Tidy up and empty the stream
return getValue<T>( "Invalid entry; try again: ", minVal, maxVal ); // Recursive call
}
if ( value < minVal || value > maxVal ) // Out of range
{
return getValue<T>( "Out of range; try again: ", minVal, maxVal ); // Recursive call
}
return value; // Good value
}
//======================================================================
int main()
{
string words[] = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };
int n = getValue<int>( "Input a digit: ", 0, 9 );
cout << "You entered ... " << words[n] << '\n';
}
//======================================================================
|