DaniWeb IT Discussion Community

DaniWeb IT Discussion Community (http://www.daniweb.com/forums/index.php)
-   C++ (http://www.daniweb.com/forums/forum8.html)
-   -   Basic Error Checking (http://www.daniweb.com/forums/thread20083.html)

Chadmo Mar 12th, 2005 11:00 pm
Basic Error Checking
 
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;}

Narue Mar 12th, 2005 11:58 pm
Re: Basic Error Checking
 
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.


All times are GMT -4. The time now is 1:02 am.

Forum system based on vBulletin Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
©2003 - 2009 DaniWeb® LLC