0

I am asking for user input for investment, I have a while loop condition for if the input is < 0 or cin.fail() and when I run the code and enter 'g' it throws an endless output of the cout statements. What am I doing wrong ?

cin >> investment;
        while ((!(investment >= 0)) || cin.fail()) {
            cout << "Please enter an amount $0 or more" << endl;
            cout << "Initial Investment Amount: $";
            cin >> investment;
        }
Farmer Gerry
  • 31
  • 1
  • 2
  • 8
  • 1
    If you want non-negative input then begin by using *unsigned* types. Then I really recommend that you read the whole line into a string instead, and then attempt to parse or convert the string contents into the type you want, for example with [`std::stoul`](https://en.cppreference.com/w/cpp/string/basic_string/stoul) to get an unsigned integer. – Some programmer dude Sep 28 '22 at 07:08
  • 3
    See e.g. https://stackoverflow.com/questions/5131647/why-would-we-call-cin-clear-and-cin-ignore-after-reading-input . – Bob__ Sep 28 '22 at 07:09
  • 4
    As an explanation about your current problem, when invalid non-numeric input is given, that won't be extracted or removed from the input buffer. The invalid input will simply stay in the input buffer forever until you remove it one way or another. *Also* you need to explicitly clear the failed status of the stream. This is why I recommend reading whole lines as strings, as it simplifies these bits. – Some programmer dude Sep 28 '22 at 07:10
  • 1
    if you input "g", cin.fail() will return true as input is not the correct type and the failed input remains in the buffer (the cin in the loop is skipped), hence the infinite loop. – charlesdk Sep 28 '22 at 07:15
  • The whole notion of validating input by letting the input fail and then recovering is flawed. Read the input as a string (which can't fail), check if the input matches your expectations (i.e. it's a non-negative integer), if it does then convert to that integer, if not then ask for more input. – john Sep 28 '22 at 07:45

0 Answers0