0

So when i enter a char or string, it asks the question again but infinitely... but i want it to ask once every time wrong, then again if wrong. Get it... ? :( right now the loop is infinite.

#include <iostream>
using namespace std;

int main() {
float money;

do
{
cout << "How much money do you have? " << endl;
cin >> money;

    if (money) {
       cout << "You have: " << money << "$" << endl;
    } else {
       cout << "You have to enter numbers, try again." << endl;
    }
} while (!money);

return 0;
}
  • `if (money)` is equivalent to `if(money != 0)`, it does _not_ check if the input was valid (You need to define what a valid input is though). it only checks the value of `money`, which is _always_ a number. – Lukas-T Mar 17 '21 at 15:35
  • 1
    Probably a non-number. Typing strings when `std::cin` should be placing them into a number type can cause this to happen. For this type of validation, I usually recommend taking it in as a string, and seeing if the conversion is fully successful. – sweenish Mar 17 '21 at 15:37
  • Does this answer your question? [Good input validation loop using cin - C++](https://stackoverflow.com/questions/2075898/good-input-validation-loop-using-cin-c) (though it depends if you want to validate only some input, or a whole line, or something else. But this should show you the general idea, especially the part about clearing and resetting `cin` ) – Lukas-T Mar 17 '21 at 15:39
  • I expect the user entered `$10` or something like that which is not a number. – drescherjm Mar 17 '21 at 15:39
  • I hadn't seen the duplicate before, I like that better than my string method, since it requires try/catch. Although, the string method can be "stricter." Input to an `int` can accept a `double` using the `std::cin` method. – sweenish Mar 17 '21 at 15:46
  • Thank you all for helping, appreciate it. – sixtyniner69 Mar 17 '21 at 15:49

1 Answers1

1

You are not validating and clearing the cin stream's error state. Try this instead:

#include <iostream>
#include <limits>
using namespace std;

int main() {
    float money;

    do
    {
        cout << "How much money do you have? " << endl;

        if (cin >> money) {
            // a valid float value was entered

            // TODO: validate the value further, if needed...

            break;
        }
        else {
            // an invalid float was entered

            cout << "You have to enter numbers, try again." << endl;

            // clear the error flag and discard the bad input...
            cin.clear();
            cin.ignore(numeric_limits<streamsize>::max(), '\n');
        }
    }
    while (true);

    cout << "You have: " << money << "$" << endl;

    return 0;
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770