How do I prevent the user from entering characters when a float is required? I'm using a bool for valid entry so if they enter text it sends my loop running

8 Years
Discussion Span
Last Post by henpecked1

after using cin call peek() to see if the next character is '\n' or not.

int x;
cin >> x;
if( cin.peek() != '\n')
    cout << "Bad\n";

Or get it as a string and check each character.


hmm, maybe I didn't give you enough info to work with. I have a while loop that uses bool to define how it runs. Entering a number is fine, works well. Entering a character provides the classic runaway loop and I'm not sure how to fix it. The code looks like this:

bool valid;
valid = false;
float usrcost=0.0;
     cout << " Please enter the CD cost " << endl;
     cin >> usrcost
     if (usrcost >0.0) valid = true;

>How do I prevent the user from entering characters when a float is required?
There's no standard way to stop a user from entering a character. You'd have to use a non-portable solution or allow anything under the sun and provide robust validation. I always recommend going for the portable solution first, and fortunately, your case is easy to validate:

bool valid = false;

do {
  cout<<"Please enter the CD cost: ";

  if ( cin>> usrcost ) {
    if ( usrcost > 0.0 )
      valid = true;
  else {
    // Clear the error state

    // Clear the stream of all characters
    cin.ignore ( 1024, '\n' );
} while ( !valid );

That worked most excellently. It did exactly what I wanted it to do (make them do it until they get it right).

I'll try to apply it to the "menu" section that I have as it has the same problem. Thanks Narue

yep, just a couple o self caused glitches, but it works well for that one too. Again, thank you.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.