Thread: Error checking

  1. #1
    Registered User
    Join Date
    Jun 2005
    Posts
    1

    Error checking

    I am working on this currency program, so far it works however whenever a user is prompted to enter an amount and enters a bunch of letters the program goes crazy. For example a user enters "afbajkdbak" - program goes in a infinite loop and I have to close the program. When a user enters "11a" the program does the error checking and the program still works. What am I doing wrong, I tried changing my code around, but still it doesn't work quite right.

    Code:
    #include <iostream.h>
    #include <stdlib.h>
    #include <stdio.h>
    #include <string.h>
    #include <iomanip.h>
    
    void main(void)
    {
       // Declaration of Variables
    	const double Jap_Rate = 1.177;  // Japanese Rate
    	const double Can_Rate = 1.021;  // Canadian Rate
       const double Bpd_Rate = 1.559;  // British Pounds Rate
    	const double Aus_Rate = 0.652;  // Australian Rate
    	const double Eur_Rate = 1.833;  // Euro Rate
    	bool bCont = true;
     	char choice;              // Hold selection of which currency is chosen
    	char curName[25];        // Hold name of currency
    	double curRate;          // Hold foreign rates
    	float usAmount;          // Hold US dollar amount
    	double convertAmount;    // Hold converted amount
    
    	do{
    	  cout << "\tCurrency Conversion Program"<< endl;
    	  cout << "\t---------------------------"<< endl << endl;
        // User will be prompted for input
    	  cout << "What currency would like to converted?" << endl;
    	  cout << "\t1 for Japanese Yen" << endl;
    	  cout << "\t2 for Canadian" << endl;
    	  cout << "\t3 for British Pounds" << endl;
    	  cout << "\t4 for Australian Dollar" << endl;
    	  cout << "\t5 for Euro" << endl;
         cout << "\t6 Exit" << endl;
         cin >> choice;
    
       // Switch for the currency type and rate
    	  switch(choice){
    		 case '1':
             strcpy(curName,"Yen");
    			curRate = Jap_Rate;
    			break;
    		 case '2':
    			strcpy(curName,"Canadian");
    			curRate = Can_Rate;
    			break;
    		 case '3':
    			 strcpy(curName,"British Pounds");
    			 curRate = Bpd_Rate;
    			 break;
    		 case '4':
    			 strcpy(curName,"Australian");
    			 curRate = Aus_Rate;
    			 break;
    		 case '5':
    			 strcpy(curName,"Euro");
    			 curRate = Eur_Rate;
    			 break;
           case '6':
              exit(1);
           default:
    			 cout << "\tTry Again" << endl << endl;
              break;
           }
    
    	  if(choice < '6'){
    	     // Get amount to be converted
    	     cout << "Enter amount to convert: ";
    	     cin >> usAmount;
            // Error checking for anything not numerical
            if(usAmount >= 0 && usAmount <= 10000){
                 // Perform conversion
    		     convertAmount = usAmount * curRate;
               // Conversion output
               // The following line formats the output to show a dollar format
               cout << setiosflags(ios::showpoint | ios::fixed) << setprecision(2);
    		     cout << "Rate as of today: " << usAmount << " of " << curName << " is ";
               cout << convertAmount << " US Dollar(s)." << endl << endl;
              }else{
                cout << "\tError: Invalid Choice." << endl << endl;
                bCont = false;  // The loop will end upon invalid input
                exit(1);
                }
              }else{
             cout << "\tError: Invalid Choice." << endl << endl;
             }
           } while(bCont);
    } // End Main

  2. #2
    Registered User
    Join Date
    Apr 2003
    Posts
    2,663
    Code:
    float usAmount;   
    ...
    ...
    cout << "Enter amount to convert: ";
    cin >> usAmount;
    If a user enters letters, then your program attempts to read letters into a float variable, and cin goes haywire in response. In order to prevent your cin stream from going into error mode, you can read everything in as a string. Then, you can use what's called a stringstream to try and obtain a number from the input. An input stringstream is like a string object but you can use the operator>> on it to try and read data into variables of any type. An input stringstream works like this:
    Code:
    #include<iostream>
    #include<string>
    #include<sstream>
    
    using namespace std;
    
    
    int main()
    {
    	string input = "12.3abc";
    	istringstream inStr(input);
    		
    	float usAmount = 0;
    		
    	inStr>>usAmount;
    	if(usAmount != 0)
    		cout<<usAmount<<endl;
    	else
    		cout<<"please enter a number"<<endl;
    	
    	
    
    	string input2 = "abc2.4";
    	istringstream inStr2(input2);
    	
    	usAmount = 0;
    
    	inStr2>>usAmount;
    	if(usAmount != 0)
    		cout<<usAmount<<endl;
    	else
    		cout<<"please enter a number"<<endl;
    
    	return 0;
    }
    Last edited by 7stud; 06-09-2005 at 01:26 AM.

  3. #3
    VA National Guard The Brain's Avatar
    Join Date
    May 2004
    Location
    Manassas, VA USA
    Posts
    903
    By adding this cin.clear( ), we can clear the instream buffer if the attempt to (cin >> useramount) fails.. we can get rid of the garbage before starting another iteration of the do/while loop:

    Code:
     }else{
             cout << "\tError: Invalid Choice." << endl << endl;
    		 
             }		 
    	 cin.clear();  //clear the instream buffer of a previous failed attempt to (cin >> float)
           } while(bCont);
    } // End Main

    Code:
    if(choice < '6'){
    	     // Get amount to be converted
    	     usAmount = 0;  //IF the user enters bogus data, at least
                                //you won't be offering a currency exchange 
                                //display leftover from a previous loop iteration.
    	     cout << "Enter amount to convert: ";
    	     cin >> usAmount;
            // Error checking for anything not numerical
            if(usAmount >= 0 && usAmount <= 10000){


    [edit] Using stringstream though is a more robust approach to handling user input [/edit]
    Last edited by The Brain; 06-09-2005 at 02:11 AM.
    • "Problem Solving C++, The Object of Programming" -Walter Savitch
    • "Data Structures and Other Objects using C++" -Walter Savitch
    • "Assembly Language for Intel-Based Computers" -Kip Irvine
    • "Programming Windows, 5th edition" -Charles Petzold
    • "Visual C++ MFC Programming by Example" -John E. Swanke
    • "Network Programming Windows" -Jones/Ohlund
    • "Sams Teach Yourself Game Programming in 24 Hours" -Michael Morrison
    • "Mathmatics for 3D Game Programming & Computer Graphics" -Eric Lengyel

Popular pages Recent additions subscribe to a feed