Help with sentinel value

Hi,

I am working on a school project and I am supposed to write a function that
takes an array as an argument, ask for inputs, and then it is suppose to print the array elements in order. So far so good. The tricky part is that if the user inputs a non numeric value, the function should terminate the inputting process and just print the numeric values that were submitted prior to the non-numeric value.

I was thinking that I could use the sentinel value:

if item inputted is not a number, then terminate function and print array content.

My problem is converting this line to code. Is there a way to make a general statement using a sentinel value?

I am trying to write a loop using something like this:

if (x != a number)

Any ideas how should I handle this?

Thanks...
You're going to want to look up Exceptions. http://www.cplusplus.com/doc/tutorial/exceptions

In the "try" statements you will want to throw an error if the input stream fails. Here is a very basic example of try, throw and catch statements (from one of my past homework assignments):


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
    float feet, inches, inchesB, tempin, cm;
    bool done = false;
    
    string str = "Input stream failed.";
    string strA = "Negative number entered.";
    string strB = "";
    
    
    cout << "This program converts feet and inches to centimeters." << endl << endl;
    do
    {
        try
        {

            cout << "Enter feet:";
            cin >> feet;
            cout << endl;
            if (!cin)
                throw str;
            if (feet < 0)
                throw feet;
                
            done = true;
            
        }
        
        catch (string message)
        {
            cout << message << endl;
            cin.clear();
            cin.ignore(100, '\n');
            cout << "Input stream restored.  Enter an integer." << endl << endl;
        }
        
        catch (float f)
        {
            cout << f << " is less than 0 and invalid." << endl;
            cout << "Enter a positive integer." << endl << endl;
            cin.clear();
            cin.ignore(100, '\n');
            
        }
        
        
    }
    while (!done);
Topic archived. No new replies allowed.