0

Aloha,

I am trying to add some basic error checking to my program. I have it only accepting the correct numbers (Positive) but when a 'char' is entered, it displays my message infinately.

Any ideas?

cout << "For DEBUG information press 1, to omit, press 0:";
cin >> DEBUG;
if ((DEBUG != 1) && (DEBUG != 0))
//this works for numbers but not letters
{cout <<"Sorry, that was not a valid entry, Please try again." << endl;
cout << "For DEBUG information press 1, to omit, press 0:";
cin >> DEBUG;}

Edited by happygeek: fixed formatting

2
Contributors
1
Reply
2
Views
12 Years
Discussion Span
Last Post by Narue
0

A good start is something along these lines:

#include <iostream>

using namespace std;

int main()
{
  int n;

  while ( !( cin>> n ) && !cin.eof() ) {
    cerr<<"Invalid input"<<endl;
    cin.clear();
    cin.ignore ( cin.rdbuf()->in_avail() );
  }

  if ( !cin.eof() )
    cout<<"You entered "<< n <<endl;
}

It still doesn't protect you from extraneous characters after a valid number, but how you deal with that is application specific.

This topic has been dead for over six months. 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.