Connecting Tech Pros Worldwide Forums | Help | Site Map

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

Newbie
 
Join Date: Feb 2008
Posts: 9
#1: May 16 '09
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's Avatar
Expert
 
Join Date: Mar 2008
Location: California
Posts: 478
#2: May 16 '09

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


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
Expand|Select|Wrap|Line Numbers
  1. if (cin.fail()) {
  2.     cin.clear();
  3.     string junk;
  4.     cin >> junk;
  5.     cout << "No more letters, please!" << endl;
  6. }
I hope this helps.
Newbie
 
Join Date: Feb 2008
Posts: 9
#3: May 17 '09

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


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,error;
char nextDay;
float weight,cost,delieveryCharge,total;

Weight is the one I want to validate

Thanks so far it has been helpful!
boxfish's Avatar
Expert
 
Join Date: Mar 2008
Location: California
Posts: 478
#4: May 17 '09

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


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.
Newbie
 
Join Date: Feb 2008
Posts: 9
#5: May 17 '09

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


Ok ill try in a minute

my whole code is currently

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



main()
{
int numberQuotes,error;
char nextDay;
float weight,cost,deliveryCharge,total;
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>>numberQuotes;
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=deliveryCharge+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(numberQuotes>0);
cout<<"\n\n PRESS ANY KEY TO EXIT";
getch();

}
Newbie
 
Join Date: Feb 2008
Posts: 9
#6: May 17 '09

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


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)


???
boxfish's Avatar
Expert
 
Join Date: Mar 2008
Location: California
Posts: 478
#7: May 17 '09

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


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

Expand|Select|Wrap|Line Numbers
  1. while (true) {
  2.     cout<<"\n Enter the weight of the package to be delivered ";
  3.     cin>>weight;
  4.     if (cin.fail()) {
  5.         // Fix it and tell the user off.
  6.     } else {
  7.         break;
  8.     }
  9. }
Newbie
 
Join Date: Feb 2008
Posts: 9
#8: May 17 '09

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


ill have a go at that now

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


Expand|Select|Wrap|Line Numbers
  1. //Program to claculate delivery cost
  2. #include <conio.h>
  3. #include <iostream.h>
  4. #include <string>
  5. main()
  6. {
  7.     int numberQuotes,error,letter;
  8.    char nextDay;
  9.    float weight,cost,deliveryCharge,total;
  10.    char pound=156; //used to display pound sign
  11.    cout<<"\n\t WELCOME TO SOLUTIONSRUS PARCEL DELIVERY CALCULATOR.";
  12.     cout<<"\n\n\t\t PRESS ANY KEY TO START";
  13.     getch();   //Waits for key to be pressed
  14.     clrscr();  //clears screen
  15.    do{
  16.         cout<<"\n How many quotes do you wish to calculate?";
  17.         cin>>numberQuotes;
  18.        if(numberQuotes<0) // if less than 0 display error message and loop back
  19.        {
  20.          cout<<"\n Error! Please enter a positive number only\n";
  21.        }
  22.        }while (numberQuotes<0); // if input less than 0 then loop back
  23.     clrscr(); //clears screen
  24.     do{
  25.             clrscr() ;  //clears screen
  26.         do{
  27.             do{
  28.             cout<<"\n Enter the weight of the package to be delivered ";
  29.                 cin>>weight;
  30.              if(weight<0) //If  weight is less than 0 then display error message
  31.              {
  32.               letter=0;
  33.                cout<<"\n Error! ENTER A POSITIVE NUMBER ONLY";
  34.              }                   
  35.                 if(weight<=1)//if weight if more than 0 or 1 set cost to 2.50
  36.                 {
  37.               letter=0;
  38.                 cost=2.50;
  39.                 }
  40.                 if (weight >1 && weight <=10)//if weight more than 1 less than/equal to 10, setcost to 7.50
  41.                 {
  42.               letter=0;
  43.                   cost=7.50;
  44.                 }
  45.                   if (weight>=10)//if weight more than or equal to 10, set cost to 10.00
  46.                 {
  47.               letter=0;
  48.                   cost=10.00;
  49.                  }
  50.                if (cin.fail())
  51.                {
  52.                  cin.clear();
  53.                     string junk;
  54.                   cin >> junk;
  55.               letter=1;
  56.                   cout << "Error! No Letters numbers only" << endl;
  57.                }
  58.               } while(letter=1);
  59.          } while (weight<0);
  60.       do{
  61.           cout<<"\n Do you require next day delivery? (Enter Y or N)";
  62.          cin>>nextDay;
  63.           if (nextDay=='Y' || nextDay=='y')
  64.           {
  65.            error=0;//sets error to 0 which means theres no error
  66.             deliveryCharge=cost/100*10 ;
  67.            total=deliveryCharge+cost ;
  68.            cout<<"\n Total charge inc next day delivery is " <<pound <<total;
  69.            cout<<"\n PRESS ANY KEY TO CONTINUE";
  70.            getch();
  71.           }
  72.              else if (nextDay=='N' || nextDay=='n')
  73.           {
  74.             error=0;//sets error to 0 which means no error
  75.            cout<<"\n Total Charge for standard delivery is " <<pound <<cost;
  76.            cout<<"\n PRESS ANY KEY TO CONTINUE";
  77.            getch();
  78.           }
  79.           else
  80.           {
  81.           error=1;//sets error to 1 which means theres an error
  82.           cout<<"Error! You have entered an invalid charater, please use Y/N";
  83.           }
  84.        }while(error==1);//while error is 1, wich means there is an error, loop back.
  85.        numberQuotes--; //Takes 1 off the number of quotes wanted.
  86.            }while(numberQuotes>0);
  87.    cout<<"\n\n PRESS ANY KEY TO EXIT";
  88.    getch();
  89.  
  90. }
  91.  
Newbie
 
Join Date: Feb 2008
Posts: 9
#9: May 17 '09

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


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
boxfish's Avatar
Expert
 
Join Date: Mar 2008
Location: California
Posts: 478
#10: May 17 '09

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


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

Expand|Select|Wrap|Line Numbers
  1. while (true) {
  2.     cout<<"\n Enter the weight of the package to be delivered ";
  3.     cin>>weight;
  4.     if (cin.fail()) {
  5.         // Fix it and tell the user off.
  6.     } else if (weight < 0)
  7.         // Tell the user off.
  8.     } else {
  9.         break;
  10.     }
  11. }
Moderator
 
Join Date: Mar 2007
Location: North Bend Washington USA
Posts: 5,381
#11: May 18 '09

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


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.
Reply

Tags
c++, char, float, validation