So, I have a couple points during the program I'm currently writing where the user provides input for an int variable. I'm trying my hardest to prevent the epic loop of fail that results from providing characters or some blend of integers and characters, so I've done some research on my own and settled on cin.clear() and cin.sync() as fitting my needs. Problem is, it doesn't always work *exactly* as intended. I'm wondering what's going wrong.
Here's an example. It's an RPG style program, so the int I'm inputting to will represent the player's gold pieces.
cout << "\nNow, please enter the amount of gold pieces you have - ";
cin >> setw(9) >> gold;
if(cin.fail())
{
failCheck = 1;
}
while(failCheck == 1)
{
cin.clear();
cin.sync();
cout << "\nThat was not a valid number.\nPlease enter the amount of gp you have - ";
cin >> setw(9) >> gold;
if(cin.good())
{
failCheck = 0;
}
}
cin.clear();
cin.sync();
pStats.setGold(gold);
Since 'gold' is an int, I used cin >> setw(9) >> gold; to hopefully prevent the user from providing numbers that are more than it can take.
Another thing that boggles me is that at the bottom of the block, I seemingly have to put the cin.clear() and cin.sync() outside for them to work properly. I initially tried having them under if(cin.good()), after failCheck = 0.
cout << "\nNow, please enter the amount of gold pieces you have - ";
while (!(cin >> gold) || gold < 0 || gold > 999999999)
{
cin.clear();
cin.sync();
cout << "\nThat was not a valid number.\nPlease enter the amount of gp you have - ";
}
pStats.setGold(gold);