summaryrefslogtreecommitdiff
path: root/appendix/useful.cxx
blob: 79dff57499db660c0417000f4d528ed6e5c525a5 (plain) (blame)
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
// FILE: useful.cxx
// IMPLEMENTS: A toolkit of functions (See useful.h for documentation.)

#include <assert.h>   // Provides assert
#include <ctype.h>    // Provides toupper
#include <iostream.h> // Provides cout, cin, get
#include <stdlib.h>   // Provides rand, RAND_MAX
#include "useful.h"

void display(double x)
// Library facilities used: iostream.h, stdlib.h
{
    const char STAR = '*';
    const char BLANK = ' ';
    const char VERTICAL_BAR = '|';
    const int  LIMIT = 39;
    int i;

    if (x < -LIMIT)
        x = -LIMIT;
    else if (x > LIMIT) 
        x = LIMIT;

    for (i = -LIMIT; i < 0; i++)
    {
        if (i >= x)
            cout << STAR;
        else
            cout << BLANK;
    }
    cout << VERTICAL_BAR;
    for (i = 1; i <= LIMIT; i++)
    {
        if (i <= x)
            cout << STAR;
        else
            cout << BLANK;
    }
    cout << endl;
}

double random_fraction( )
// Library facilities used: stdlib.h
{
    return rand( ) / double(RAND_MAX);
}

double random_real(double low, double high)
// Library facilities used: assert.h
{
    assert(low <= high);
    return low + random_fraction( ) * (high - low);
}

void eat_line( )
// Library facilities used: iostream.h
// 
{
    char next;

    do
        cin.get(next);
    while (next != '\n');
}

bool inquire(const char query[ ])
// Library facilities used: ctype.h, iostream.h
{
    char answer;
    do
    {
        cout << query << " [Yes or No]" << endl;
        cin >> answer;
        answer = toupper(answer);
        eat_line( );
    }
    while ((answer != 'Y') && (answer != 'N'));
    return (answer == 'Y');
}