Jump to content
  • Advertisement
Sign in to follow this  
Mark04

Field Validation

This topic is 4996 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi. How can I check a text field in C++ to ensure that it does not contain letters, or symbols. Only numberic values allowed? Thanks in advance Mark [Edited by - Mark04 on March 16, 2005 2:42:09 PM]

Share this post


Link to post
Share on other sites
Advertisement
If you're using std::string:


std::string sValue = "<input>";
if(sValue.find_first_not_of("0123456789") == std::string::npos) {
// Input contains only numeric characters
return success;
} else {
// Input contains non-numeric characters
return error;
}



[edit]Simplified check[/edit]

Share this post


Link to post
Share on other sites

struct notNumber
{
//Functor to check if a character isn't a digit.
struct notDigit
{
operator()(char const &c)
{
return c < '0' || c > '9';
}
};
//Return true if field is not a number.
bool operator()(string const &field)
{
return find_if(field.begin(), field.end(), notDigit()) != field.end();
}
};




The above notNumber functor will check if a std::string meets contains any character other than [0-9].

Share this post


Link to post
Share on other sites
Quote:
Original post by gisdev
If you're using std::string:

*** Source Snippet Removed ***

[edit]Simplified check[/edit]


I like that better.

Share this post


Link to post
Share on other sites
it doesn't work with -5 or 3.142 or 1e-7

If you want to deal with those properly you'll need to look into locales. For example some countries would have 3,142 instead of 3.142.

Personally I would use boost.lexical_cast and let it worry about whether the conversion is correct.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!