Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


advertisement
 

Using String-based Data Validation-2 : Page 2


advertisement
What Is Wrong with Datatype Analysis?
Suppose we want to develop a typical online flight booking system in which the user fills out the number of passengers, the requested date, the destination, the name etc. We need to determine the underlying types of each of the fields that the user should enter. For instance, the number of passengers is int whereas a passenger's name is of type string:

class booking { private: int passengers; string name; //.. };

We then read these fields as follows:



void booking::get_details() { cout<< "enter number of passengers: "<< endl; cin>>passengers; // }

Alas, cin doesn't block users from entering patently wrong data. If the user inserts the string "2w" as the number of passengers, cin will treat the letter 'w' as the beginning of the next field. Thus, not only do we end up with a dubious number of passengers, but the next field will contain a garbage value. As a partial solution, we can check the state of cin after each input operation by calling fail(). If cin is in an anomalous condition, fail() returns true. To see how it works, call get_details() again and insert the string "zz" as the number of passengers:

enter number of passengers: zz

As expected, a subsequent call to cin.fail() returns true. Yet we can't tell what exactly is wrong with the input; all we know is that the user has entered an incorrect value (at this point, our passenger field contains a garbage value). To fix this, we can read the input in a loop, asking the users to re-enter this datum if fail() is true. This, however, isn't an ideal solution for several reasons. To begin with, we don't know what exactly is wrong with the input, so we can't give the users a detailed error message. Furthermore, cin doesn't clear the error automatically; you'd have to call clear() to clear the error. Obviously, we need a better validation method.



Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date