C++ : Do not allow letters in a float validation?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • halljkl
    New Member
    • Feb 2008
    • 9

    C++ : Do not allow letters in a float validation?

    I have to create a program that has validation in it, The programme asks the user for the weight of a package, and sets the cost appropriately, I have a do in place do that if the user types in a minus number it gives them an error.

    do{
    clrscr();
    cout<<"\n Enter the weight of the package to be delivered ";
    cin>>weight;
    if(weight<0)
    {
    cout<<"\n Error! ENTER A POSITIVE NUMBER ONLY";
    }
    if(weight<=1)
    {
    cost=2.50;
    }
    if (weight >1 && weight <=10)
    {
    cost=7.50;
    }
    if (weight>=10)
    {
    cost=10.00;
    }
    } while(weight<0) ;


    But how to I stop the user entering a letter when it should be numbers only?
    Thanks In Advance
  • boxfish
    Recognized Expert Contributor
    • Mar 2008
    • 469

    #2
    If the user enters a letter, the cin.fail flag will be raised. You will need to clear it with cin.clear and remove the offending letter or letters from the stream somehow. Do something like
    Code:
    if (cin.fail()) {
        cin.clear();
        string junk;
        cin >> junk;
        cout << "No more letters, please!" << endl;
    }
    I hope this helps.

    Comment

    • halljkl
      New Member
      • Feb 2008
      • 9

      #3
      I tried this but can you tell me how to put it into my code?

      Currently I have included
      #include <conio.h>
      #include <iostream.h>

      and have declared


      int numberQuotes,er ror;
      char nextDay;
      float weight,cost,delievery Charge,total;

      Weight is the one I want to validate

      Thanks so far it has been helpful!

      Comment

      • boxfish
        Recognized Expert Contributor
        • Mar 2008
        • 469

        #4
        To use the code I posted, you need to include <string>. I don't like having to include another header file just to put junk in, but it's the easiest way to do it.

        Comment

        • halljkl
          New Member
          • Feb 2008
          • 9

          #5
          Ok ill try in a minute

          my whole code is currently

          #include <conio.h>
          #include <iostream.h>



          main()
          {
          int numberQuotes,er ror;
          char nextDay;
          float weight,cost,del iveryCharge,tot al;
          char pound=156; //used to display pound sign
          string weight;

          cout<<"\n\t WELCOME TO SOLUTIONSRUS PARCEL DELIEVERY CALCULATOR.";
          cout<<"\n\n\t\t PRESS ANY KEY TO START";
          getch();
          clrscr();
          do{
          cout<<"\n How many quotes do you wish to calculate?";
          cin>>numberQuot es;
          if(numberQuotes <0)
          {
          cout<<"\n Error! Please enter a positive number only\n";
          }
          }while (numberQuotes<0 );
          clrscr();
          do{
          clrscr()
          do{

          cout<<"\n Enter the weight of the package to be delivered ";
          cin>>weight;
          if(weight<0)
          {
          cout<<"\n Error! ENTER A POSITIVE NUMBER ONLY";
          }
          if(weight<=1)
          {
          cost=2.50;
          }
          if (weight >1 && weight <=10)
          {
          cost=7.50;
          }
          if (weight>=10)
          {
          cost=10.00;
          }
          } while(weight<0) ;
          do{
          cout<<"\n Do you require next day delievey? (Enter Y or N)";

          cin>>nextDay;
          if (nextDay=='Y' || nextDay=='y')
          {
          error=0;
          deliveryCharge= cost/100*10 ;
          total=deliveryC harge+cost ;
          cout<<"\n Total charge inc next day delievery is " <<pound <<total;
          cout<<"\n PRESS ANY KEY TO CONTINUE";
          getch();
          }
          else if (nextDay=='N' || nextDay=='n')
          {
          error=0;
          cout<<"\n Total Charge for standard delievery is " <<pound <<cost;
          cout<<"\n PRESS ANY KEY TO CONTINUE";
          getch();
          }
          else
          {
          error=1;
          cout<<"Error! You have entered an invalid charater, please use Y/N";
          }
          }while(error==1 );
          numberQuotes--;
          }while(numberQu otes>0);
          cout<<"\n\n PRESS ANY KEY TO EXIT";
          getch();

          }

          Comment

          • halljkl
            New Member
            • Feb 2008
            • 9

            #6
            YES YES YES !!!!! THANKS SOOOOOOOO Much!!

            Just 1 more question. How can I loop it back so that the user has another go at entering a number. Can i not do a

            do{

            }while(cin.fail )


            ???

            Comment

            • boxfish
              Recognized Expert Contributor
              • Mar 2008
              • 469

              #7
              It's tricky to do this without telling the user off before he/she has entered anything. Here is what I would do:

              Code:
              while (true) {
                  cout<<"\n Enter the weight of the package to be delivered ";
                  cin>>weight;
                  if (cin.fail()) {
                      // Fix it and tell the user off.
                  } else {
                      break;
                  }
              }

              Comment

              • halljkl
                New Member
                • Feb 2008
                • 9

                #8
                ill have a go at that now

                but is something wrong with this? It once a letter is entered is wont accept a number


                Code:
                //Program to claculate delivery cost
                #include <conio.h>
                #include <iostream.h>
                #include <string>
                main()
                {
                	int numberQuotes,error,letter;
                   char nextDay;
                   float weight,cost,deliveryCharge,total;
                   char pound=156; //used to display pound sign
                   cout<<"\n\t WELCOME TO SOLUTIONSRUS PARCEL DELIVERY CALCULATOR.";
                	cout<<"\n\n\t\t PRESS ANY KEY TO START";
                	getch();   //Waits for key to be pressed
                	clrscr();  //clears screen
                   do{
                   	 cout<<"\n How many quotes do you wish to calculate?";
                   	 cin>>numberQuotes;
                       if(numberQuotes<0) // if less than 0 display error message and loop back
                       {
                         cout<<"\n Error! Please enter a positive number only\n";
                       }
                 	  }while (numberQuotes<0); // if input less than 0 then loop back
                    clrscr(); //clears screen
                    do{
                    		clrscr() ;  //clears screen
                    	do{
                    		do{
                            cout<<"\n Enter the weight of the package to be delivered ";
                				cin>>weight;
                         	if(weight<0) //If  weight is less than 0 then display error message
                         	{
                              letter=0;
                         	  cout<<"\n Error! ENTER A POSITIVE NUMBER ONLY";
                         	}                   
                				if(weight<=1)//if weight if more than 0 or 1 set cost to 2.50
                				{
                              letter=0;
                      		  cost=2.50;
                				}
                				if (weight >1 && weight <=10)//if weight more than 1 less than/equal to 10, setcost to 7.50
                				{
                              letter=0;
                				  cost=7.50;
                				}
                	  			if (weight>=10)//if weight more than or equal to 10, set cost to 10.00
                				{
                              letter=0;
                				  cost=10.00;
                	 			}
                           	if (cin.fail())
                           	{
                			     cin.clear();
                  				  string junk;
                    			  cin >> junk;
                              letter=1;
                				  cout << "Error! No Letters numbers only" << endl;
                           	}
                     	     } while(letter=1);
                         } while (weight<0);
                      do{
                	      cout<<"\n Do you require next day delivery? (Enter Y or N)";
                         cin>>nextDay;
                      	if (nextDay=='Y' || nextDay=='y')
                      	{
                           error=0;//sets error to 0 which means theres no error
                      	  deliveryCharge=cost/100*10 ;
                           total=deliveryCharge+cost ;
                           cout<<"\n Total charge inc next day delivery is " <<pound <<total;
                           cout<<"\n PRESS ANY KEY TO CONTINUE";
                           getch();
                      	}
                     		else if (nextDay=='N' || nextDay=='n')
                      	{
                      	  error=0;//sets error to 0 which means no error
                           cout<<"\n Total Charge for standard delivery is " <<pound <<cost;
                           cout<<"\n PRESS ANY KEY TO CONTINUE";
                           getch();
                      	}
                      	else
                      	{
                      	error=1;//sets error to 1 which means theres an error
                      	cout<<"Error! You have entered an invalid charater, please use Y/N";
                      	}
                       }while(error==1);//while error is 1, wich means there is an error, loop back.
                       numberQuotes--; //Takes 1 off the number of quotes wanted.
                  	 	}while(numberQuotes>0);
                   cout<<"\n\n PRESS ANY KEY TO EXIT";
                   getch();
                
                }

                Comment

                • halljkl
                  New Member
                  • Feb 2008
                  • 9

                  #9
                  I dont know what im doing but I just cant get it to work, with your help I feel I am a bit further on but cant get it to work properly

                  Comment

                  • boxfish
                    Recognized Expert Contributor
                    • Mar 2008
                    • 469

                    #10
                    You need to be checking cin.fail before you do anything with the number, because if the user enters a letter then the number may contain a garbage value. You should probably be dealing with negative numbers and letters in the same loop. Something like

                    Code:
                    while (true) {
                        cout<<"\n Enter the weight of the package to be delivered ";
                        cin>>weight;
                        if (cin.fail()) {
                            // Fix it and tell the user off.
                        } else if (weight < 0)
                            // Tell the user off.
                        } else {
                            break;
                        }
                    }

                    Comment

                    • weaknessforcats
                      Recognized Expert Expert
                      • Mar 2007
                      • 9214

                      #11
                      The C++ >> operator is for formatted input. That is, you already know the type of data in the input stream. Therefore, there shouldn't be any failures.

                      If there are, like cin.fail() is true, then the entire input stream is now bogus and needs to be cleaned out. Then you can call cin.clear() to reset the fail bit.

                      When you are in a situation where you don't know what data is in the input stream, like for user input, then you need to get crafty.

                      You could:

                      1) cin >> to an integer. If this works, you are done.
                      2) Otherwise, call cin.clear() and try cin >> to a double. If this works, you are done.
                      3)Otherwise, call cin.clear(), and cin >> to a string. If this works you are done.
                      4) Otherwise, you may be at the point of terminating the program.

                      Another approach is to not use the >> operator at all but use cin.get() instead. Now you can look at each byte and decide what to do with it.

                      However you do it, make sure your function that fetches the data has an istream& argument. That way you can use the function when the input stream is a disc file or something else other than stdin.

                      Comment

                      Working...