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

Recommended Answers

All 4 Replies

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;
while(valid!=true)
{
     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
    cin.clear();

    // 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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.