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.
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.
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 )
{
unsignedint 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 )
returntrue;
elsereturnfalse;
}
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";
}