Do while loop.. right now: infinite, goal: not infinite (ask until loop)

Issue

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;
}

Solution

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;
}

Answered By – Remy Lebeau

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published