How to check if a CString contains only numeric characters

I read from a file and parse its contents. I need to make sure that the CString value consists only of numbers. What methods can I achieve?

Code example:

 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"; } } 
+7
source share
2 answers

You can isdigit over all the characters and check with the isdigit function 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"); } 
+14
source

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 MSDN

+1
source

All Articles