So I'm a newbie and I keep getting an anomaly when I try to validate my input.
I can't figure out what I'm doing wrong.
I am learning all about classes an header files, so I thought I'd make an inventory/shop interaction program.
I ask the user to input an item from the shop that I will later store in their inventory.
I need to validate that the user has input an integer (not an alpha/char) and that the integer is between 1 and 5. I managed to do that, but every time I put in a correct integer it forces me to input it twice and only retains the second input; this is my main problem and I need your help to fix it. :)
Also, I want to know how to prevent the error message from running one time for every incorrect character in a string or large number. I want it to only print the error message once, no matter what the input is.
You'll likely have to run the program to see what I mean. So here are the files below.
Run the program and:
1) type in a correct choice to see the anomaly.
2) type in an alpha character incorrect integer to see the "wrong input message".
3) type in a long word or number to see the repeated error message anomaly.
4) I know the program isn't totally finished I just want correct error messages to function in most circumstances.
THANKS A TONNE FOR ANY HELP!!!
And all good if it's too much of a pain in the ass, just pass on by, and happy future coding to you :D
3) type in a long word or number to see the repeated error message anomaly.
You probably want to ignore more than one character when you have a stream error. You need to remove all the characters in the input stream before you loop, not one character. Look up the documentation for the ignore() function to see how to properly clear the input buffer.
And don't forget that the extraction operator>> stops processing when it encounters white space characters or invalid characters leaving everything else in the input buffer for the next input operation.
I guess you are trying to get a new (better) choice from the user here after they entered a wrong value. Unfortunately, your if statement is true for the valid answers instead of the invalid answers, which is why you have your "anomaly".
Try it like:
1 2 3 4 5 6 7 8 9 10 11
cin >> purchase;
}
while((purchase > 6) || (purchase < 0)) // if purchase is not valid, keep doing this until it is valid.
{
cin.clear();
cin.ignore();
cout << "The value you choose is incorrect, please choose again: ";
cin >> purchase;
}
cout << "You choose number: " << purchase << ". " << "Let me get that for you. \n";
You don't need an if statement, if the condition of a while loop is not true initially, the whole loop will be skipped (unlike a do-while loop that is always executed at least once).