Reputation: 47
Is there any way to check if the input to a string is in the range of 00 to 99?
I am creating a class for money and because float isnt recommended i thought of getting the input into two strings. One for euros and one for cents. After this, combining the strings and streaming them out to an int Long. But the problem is, if the user uses too few or to many digits in cents, than the whole thing will become a disaster
void Money::deposit() {
cout << "How much do you want to deposit? (Euros [ENTER], Cents [ENTER)" << endl;
string euros, cents;
cout << "Deposit: " << flush; cin >> euros; cout << "," << flush; cin >> cents;
}
Upvotes: 2
Views: 160
Reputation: 131519
I suggest you take the amount of money as a string first, then analyze the string - look for the decimal dot (if any), decide whether you like the number of digits (= digit character) the user provided for cents, etc. The std::string
class has many relevant methods you could use for this purpose.
The benefit is that you'll be avoiding potential parsing failures and having to deal with annoying iostream semantics.
Note, however, that this solution is very rudimentary and would not be usable in other locales and/or for other currencies. Or rather, you would need to rewrite a lot of code other people have written. If you want to do this "seriously", look for existing libraries for working with currency values, possibly locale-aware libraries.
Upvotes: 3