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
|
#include <iostream>
#include <limits>
using namespace std;
//----------------------------------------------------------------------------
// This is your message() function, fixed in certain ways.
// Remember, cin>>foo means that 'foo' is input. You've gotten
// yourself into naming troubles because you have two variables
// that represent the same thing, and the input is also the function's
// return value. I would re-think what exactly it is you are trying to do...
//
// Also, you cannot hard-code a value like zero in a comparison if the
// object may not be a numeric type. I'm not sure why you did this,
// especially as your original program never initialized main()::value,
// so whether or not the function returns a result in value is undefined.
//
template <typename ValueType>
ValueType message(
const string& mess,
ValueType& result,
const ValueType& result_must_differ_from_this_to_be_assigned
) {
ValueType input;
cout << mess << endl;
cin >> input;
if (result != result_must_differ_from_this_to_be_assigned)
result = input;
return input;
}
//----------------------------------------------------------------------------
// Here's another datatype (other than integer) to play with.
// It is just a string that >> reads terminating at newline instead of
// any-old whitespace.
//
typedef string linestring;
inline istream& operator >> ( istream& ins, linestring& s )
{
return getline( ins, s );
}
//----------------------------------------------------------------------------
// And here's the main function, much like your example.
// Notice how value1 will not be modified, but value2 will (since 42 != ~42).
//
int main()
{
int value1 = 0;
int value2 = 42;
message( "Enter an integer", value1, 0 );
message( "Enter another", value2, ~42 );
cout << "value1 = " << value1 << '\n'
<< "value2 = " << value2 << '\n';
// Get rid of that extra newline waiting in the input after reading value2
cin.ignore( numeric_limits <streamsize> ::max(), '\n' );
// Play with strings instead of system()
linestring foo;
message( "Press Enter to quit...", foo, linestring( "\1" ) );
if (!foo.empty())
{
cout << "Ah, but \"" << foo << "\" is more than just 'Enter'. :-)\n";
}
return 0;
}
|