Skip to main content
gamedev.net
🔒 Locked

Field Validation

Started by Mark04 Mar 16, 2005 at 2:10 PM 3 replies 1.2k views
Original Post
Mark04
Mark04
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]
gisdev
gisdev
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]
Couvillion
Couvillion
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].
~~C--O -
Couvillion
Couvillion
Quote:
Original post by gisdev
If you're using std::string:

*** Source Snippet Removed ***

[edit]Simplified check[/edit]


I like that better.
~~C--O -
Qw3r7yU10p!
Qw3r7yU10p!
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.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.