James
James

Reputation: 319

using cin to close a while loop

I'm trying to verify my user input using a while loop. Please see below for my code/while loop. I want them to enter a float number, and I'm trying to verify that they have entered a number rather then a letter/sentence. I think this loop should work but when I run it if I enter a number it craps out before reaching the end of the program and if I enter a string it touches the cout statement, fails to ask for the cin, and then validates the loop. If you could explain what and why is happening as well as how to fix it I would really appreciate it.

#include <iostream>   
using namespace std;

int main()
{
    float mph, i = 0;
    cout << "this program will calculate the distance a train will travel in a given amount of time." << endl;
    cout << "What is the speed of the vehicle in mph? ";
    cin >> mph;
    cout << endl;


    while (mph > -3.4E-38 && mph < 3.4E38);
    {
        cout << "that is not a number, do not pass go, do not collect $200 but DO try again." << endl;
        cin >> mph;
        // trace statement to check whats happening in the loop
        cout << "trace: " << mph << "faluer: " << i << endl;
        i++;
    }
    cout << "works twice" << endl;

    system("pause");
    return 0;
}

Upvotes: 0

Views: 533

Answers (1)

AliciaBytes
AliciaBytes

Reputation: 7439

You should change your code inside the while loop to something like:

cout<<"that is not a number, do not pass go, do not collect $200 but DO try again."<<endl;

if (!cin) { // we enter the if statement if cin is in a "bad" state.
    cin.clear(); // first we clear the error flag here
    cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // now we skip the input,
                                                                   // that led to the invalid state
}

cin>>mph;

if you enter a string and try to read it into a float with cin, cin goes into invalid state and refuses to read any input until cleared.
That's what my suggested code above tries to fix. Note that you got to include <limits> for it to work.

Related link for more information on clearing the input stream: Why is this cin reading jammed?

Upvotes: 3

Related Questions