Basic Error Checking

Reply

Join Date: Mar 2005
Posts: 1
Reputation: Chadmo is an unknown quantity at this point 
Solved Threads: 0
Chadmo Chadmo is offline Offline
Newbie Poster

Basic Error Checking

 
0
  #1
Mar 12th, 2005
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;}
Reply With Quote Quick reply to this message  
Join Date: Sep 2004
Posts: 7,541
Reputation: Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute 
Solved Threads: 704
Team Colleague
Narue's Avatar
Narue Narue is offline Offline
Code Goddess

Re: Basic Error Checking

 
0
  #2
Mar 12th, 2005
A good start is something along these lines:
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. int main()
  6. {
  7. int n;
  8.  
  9. while ( !( cin>> n ) && !cin.eof() ) {
  10. cerr<<"Invalid input"<<endl;
  11. cin.clear();
  12. cin.ignore ( cin.rdbuf()->in_avail() );
  13. }
  14.  
  15. if ( !cin.eof() )
  16. cout<<"You entered "<< n <<endl;
  17. }
It still doesn't protect you from extraneous characters after a valid number, but how you deal with that is application specific.
I'm here to prove you wrong.
Reply With Quote Quick reply to this message  
Reply

This thread is more than three months old.
Perhaps start a new thread instead?
Message:


Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC