2

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;

}
Newbie2018
  • 47
  • 8
  • How many is `too few`? – Killzone Kid Apr 09 '18 at 19:30
  • 1
    While it's great that you're aware of floating-point precision problems, take a look at [this post](https://stackoverflow.com/questions/149033/best-way-to-store-currency-values-in-c) that has some great answers on how to store currency values. – Nick Apr 09 '18 at 19:31
  • @KillzoneKid should be two digits, from 00 up to 99, så minimum and maximum of two digits – Newbie2018 Apr 09 '18 at 19:32
  • You can certainly examine `cents.size()` to see if it has the number of characters you want. And you can use `::isdigit()` on each character to be sure it is a digit. E.g., `if (::isdigit(cents[0])) {do something}` – vacuumhead Apr 09 '18 at 19:35
  • @vacuumhead thank you! do you know if it is possible for the next cin to be in the same row as the first? As you can see i have inserted "," after the first cin, but even tho i have flush after it, the cin for cents goes to the new row. – Newbie2018 Apr 09 '18 at 19:39

1 Answers1

3

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.

einpoklum
  • 118,144
  • 57
  • 340
  • 684