8

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";
  }
}
Rohit Vipin Mathews
  • 11,629
  • 15
  • 57
  • 112

2 Answers2

21

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");
}
Ivan
  • 4,383
  • 36
  • 27
halex
  • 16,253
  • 5
  • 58
  • 67
  • Could this be possible by only using `CString` function? Isnt it C++ style to use isdigit? – Rohit Vipin Mathews Oct 08 '12 at 07:29
  • @Rohit I don't know of a `CString` method that checks if the whole string or parts are numeric. `isdigit` is even a C function, but it's standardized and you won't have problems using it:) – halex Oct 08 '12 at 07:34
  • 1
    @Rohit I found a way only using CString member functions. See edit – halex Oct 08 '12 at 07:44
  • `isdigit` assumes the input characters are bytes in the local code page, (or sometimes it assumes ASCII), and `CString` normally holds UTF-16. – Mooing Duck Jun 16 '14 at 18:22
  • Would it be a little more efficient to compare the length of the SpanIncluding result with the length of the string instead of doing a string compare? The string compare ends up comparing each character if they are identical strings. – David Rector Aug 03 '16 at 02:28
0

you can use CString::Find,

int Find( TCHAR ch ) const;

int Find( LPCTSTR lpszSub ) const;

int Find( TCHAR ch, int nStart ) const;

int Find( LPCTSTR pstr, int nStart ) const;

Example

CString str("The stars are aligned");
int n = str.Find('e')
if(n==-1)   //not found
else        //found

See here In MSDN

jiten
  • 5,128
  • 4
  • 44
  • 73