Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a CString contains only numeric characters

I'm reading from a file and parsing its contents. I need to make sure a CString value consist of only numbers. What are the different methods i could achieve it?

Sample code:

Cstring Validate(CString str)
{
  if(/*condition to check whether its all numeric data in the string*/)
  {
     return " string only numeric characters";
  }
  else
  {
     return "string contains non numeric characters";
  }
}
like image 990
Rohit Vipin Mathews Avatar asked Oct 08 '12 07:10

Rohit Vipin Mathews


1 Answers

You can iterate over all characters and check with the function isdigit whether the character is numeric.

#include <cctype>

Cstring Validate(CString str)
{
    for(int i=0; i<str.GetLength(); i++) {
        if(!std::isdigit(str[i]))
            return _T("string contains non numeric characters");
    }
    return _T("string only numeric characters");
}

Another solution that does not use isdigit but only CString member functions uses SpanIncluding:

Cstring Validate(CString str)
{
    if(str.SpanIncluding("0123456789") == str)
        return _T("string only numeric characters");
    else
        return _T("string contains non numeric characters");
}
like image 167
halex Avatar answered Sep 26 '22 19:09

halex