Basic Boolean function

I have an incredibly basic function to create but my mind just won't make the connection. It prototypes as:
bool get ( int & a, int & b)
and it needs to accept keyboard input of two integers. If it obtains a and b successfully the value is true, otherwise it's false.

So what do I need to do?
Last edited on
You can read an integer with cin >> a;
Yeah I understand that. But for some reason I'm not getting how to set the true condition.
If the user enters a = 0, b = 0, that's true. If they enter a = 1, b = 1, that's true.
Then what should be false?
Anything that isn't an integer. a = J wouldn't be valid.
You check the stream's good bit to see how the conversion from string to int went.

1
2
3
4
5
6
7
8
9
int x;
cout << "Enter an integer value: ";
cin >> x;
if (!cin.good())
  {
  cin.clear();
  cout << "Hey you, that wasn't an integer value!\n";
  }
cin.ignore( numeric_limits <streamsize> ::max(), '\n' );

Hope this helps.
Sorry, how is that related to my Boolean function? I thought it was simpler than that at any rate.
If it failed to convert it properly to a number, such as if there were characters other than 0-9 (eg a letter) that messed it up, then you obviously know that they didn't enter a valid number.
Okay, I get what Duoas' code is doing, but I don't understand how it connects back to the prototype.
I don't have any talent for programming, but I am trying I promise, I do a lot of reading and testing before I come here.
If I understand correctly your function will try to get two integer values from the user. If the user enters two valid numbers, the function will return "true", or else the function will return "false".

Now, if my understanding is correct, your function could look like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
bool get ( int & a, int & b )
{
    unsigned int first_check, second_check;

    cout << "Please enter an integer value: ";
    cin >> a;

    first_check = cin.good ( );
    
    cout << "Please enter another integer value: ";
    cin >> b;

    second_check = cin.good ( );

    if ( first_check && second_check )
        return true;
    else
        return false;
}


And then you could use your function in the following way:
1
2
3
4
5
6
7
8
9
10
11
// Safely get two numbers from the user
while ( true )
{
    if ( get ( a, b ) )
    {
        // Do something
        break;
    }
    else
        cout << "Error: you entered an invalid number. Please try again. \n";
}


I hope this helps ;)
It certainly did. It's still not working for me but I'll modify it a bit and try again.
Topic archived. No new replies allowed.