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
|
#include <iostream>
#include <cassert>
int get_integer( const char* prompt )
{
int number ;
std::cout << prompt << "? " ;
if( std::cin >> number ) return number ;
std::cout << "error in input. please try again\n" ;
std::cin.clear() ; // clear the error state
std::cin.ignore( 1000, '\n' ) ; // throw away the junk
return get_integer(prompt) ; // try again
}
void get_data( int& x, int& y )
{
x = get_integer( "first number" ) ;
y = get_integer( "second number" ) ; ;
}
int sum( int x, int y ) { return x+y ; }
int difference( int x, int y ) { return x-y ; }
int product( int x, int y ) { return x*y ; }
int quotient( int x, int y ) { assert( y != 0 ) ; return x/y ; }
int remainder( int x, int y ) { assert( y != 0 ) ; return x%y ; }
void print_results( int x, int y, int sum, int difference, int product )
{
std::cout << x << '+' << y << " == " << sum << '\n'
<< x << '-' << y << " == " << difference << '\n'
<< x << '*' << y << " == " << product << '\n' ;
}
void print_div_results( int x, int y, int quotient, int remainder )
{
std::cout << x << '/' << y << " == " << quotient << '\n'
<< x << '%' << y << " == " << remainder << '\n' ;
}
void process_data( int x, int y )
{
print_results( x, y, sum(x,y), difference(x,y), product(x,y) ) ;
if( y != 0 ) print_div_results( x, y, quotient(x,y), remainder(x,y) ) ;
}
bool run_again()
{
std::cout << "run again? (y/n): " ;
char c ;
std::cin >> c ;
return c == 'y' || c == 'Y' ;
}
void run_once()
{
int x, y ;
get_data( x, y ) ;
process_data(x,y) ;
}
int main()
{
do run_once() ;
while( run_again() ) ;
}
|