How to check if a string is digits or just alphanumeric?  
Author Message
Bassam72





PostPosted: Visual C++ Language, How to check if a string is digits or just alphanumeric? Top

Dear folk

During my programming, I came across a specific check procedure to a string. sometimes this string contains alphanumeric and othertimes it contains numbers. My question is how to check the contents of that string whether they are digits or alphanumeric

A simple code is shown below:


Visual C++12  

 
 
einaros





PostPosted: Visual C++ Language, How to check if a string is digits or just alphanumeric? Top

Here's one way to do it using the count_if standard algorithm:

#include <string>
#include <algorithm>

using namespace std;

int main()
{
string foo = "123";

if(count_if(foo.begin(), foo.end(), isdigit) == foo.size())
{
// is all digits
}
else if(count_if(foo.begin(), foo.end(), isalnum) == foo.size())
{
// is all alpha numerical
}
else
{
// ...
}
}