Hi, I read the question again. The question says "prompts the user for an integer and uses a loop to validate it using the minimum given in the parameter set."
Also, the example it gives :
Please enter an integer (min: 15, exit: -1): 13
Invalid input, try again!
Please enter an integer (min: 15, exit: -1): -10
Invalid input, try again!
Please enter an integer (min: 15, exit: -1): 17
Please enter an integer (min: 15, exit: -1): -1
so it looks like the program will first prompts user with "Please enter an integer (min: 15, exit: -1):", and if user enter number lower than min(which is 15 in sample), the program will keep showing "Invalid input, try again!" and "Please enter an integer (min: 15, exit: -1):" until user enter number larger than 15 or -1(which is sentinel).
Therefore, you can imagine that there is an "infinite loop" keep showing "Please enter an integer (min: 15, exit: -1):" and "Invalid input, try again!" until you enter number larger than 15 or -1(which is sentinel), which can break the loop and jump out. After that, the function should return the valid value or -1.
i modify your first code with my imagine as below:
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
|
int inputVal(int min, int sentinel)
{
//Get integer value
int integer;
/*Below is infinite loop to keep saying "Please enter an integer (min: 15, exit: -1): " and "invalid
input, try again!"*/
while (1)
{
//Prompt user for integer value
cout << "Please enter an integer (min: 15, exit: -1): ";
cin >> integer;
/*check if user enter number larger than 15 or same as sentinel(-1) so that
program can break and jump out of loop*/
if(integer>=15||integer==sentinel)
{
break;
}
if(integer < 15)
{
cout << "invalid input, try again!";
}
//cin >> integer; // this line duplicated so i set it as comment
}
//after break the loop, we should assign the valid-user-input to sentinel, so it can return
sentinel=integer;
return sentinel;
}
int main()
{
int x = inputVal(15, -1);
/*in case you need to check what number user type, I output x, which is return value
from sentinel of function inputVal*/
cout<<x<<endl;
system("pause");
return 0;
}
|
I didn't add carriage return, so it won't look like the same as sample. please help yourself to add it.
Also, I guess the last two line sample example:
Please enter an integer (min: 15, exit: -1): 17
Please enter an integer (min: 15, exit: -1): -1
which is showing correct case, so it doesn't have "Invalid input, try again!"
feel free to let me know if I misunderstand the question. thanks