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 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
|
#include <ciso646>
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
//----------------------------------------------------------------------------
template <typename T>
bool string_to( const std::string& s, T& result )
{
// Convert string argument to T
std::istringstream ss( s );
ss >> result >> std::ws;
// Stream should be in good standing with nothing left over
return ss.eof();
}
template <typename T>
T string_to( const std::string& s )
{
T result;
if (!string_to( s, result ))
throw std::invalid_argument( "T string_to <T> ()" );
return result;
}
//----------------------------------------------------------------------------
int input_integer( const char* prompt, const char* reprompt, int min, int max )
{
int x;
cout << prompt;
while (true)
{
// Get user input as a string (user presses ENTER when done)
string s;
getline( cin, s );
// Convert string to int and validate
if (string_to( s, x ) and (x >= min) and (x <= max)) break;
// If validation failed, prompt for try again
cout << reprompt;
}
return x;
}
int input_days_in_month()
{
return input_integer(
"Enter the number of days in the month (28-31): ",
"Invalid number of days. Try again: ",
28, 31 );
}
int input_temperature( const char* prompt )
{
return input_integer(
prompt,
"Invalid temperature. Try again: ",
-200, 200
);
}
//----------------------------------------------------------------------------
int main()
{
int month;
int minTemp;
int maxTemp;
int mmRainfall;
int totalMmRainfall;
month = input_days_in_month();
for (int i = 0; i < month; ++i)
{
cout << "Day " << i+1 << ": " << endl;
minTemp = input_temperature( "Enter the lowest temperature (as a whole number): " );
maxTemp = input_temperature( "Enter the highest temperature (as a whole number): " );
mmRainfall = input_integer(
"Enter the amount of rainfall in mm: ",
"Invalid. Try again: ",
0, 1000 );
}
// system("pause");
return 0;
}
|