Sid
Sid

Reputation: 275

Verify a CString like "-2-2" or "--22" or "2--2" is not a valid

In C++ how to verify a CString like "-2-2" or "--22" or "2--2" is not a valid integer.

I tried the following code :

// CString input in the edit box that needs to be verified
   CString input_to_editbox
// verify its a number or not
   if (input_to_editbox.SpanIncluding(L"-0123456789") == input_to_editbox)
   //numeric
   AfxMessageBox(L"it is an integer");
   else
   //Non numeric
   AfxMessageBox(L"Not an integer");

But I am not able to verify that "-2-2" or "--22" or "2--2" is illegal and bad integer.

Upvotes: 0

Views: 134

Answers (1)

Werner Henze
Werner Henze

Reputation: 16761

I have come across the same problem when using the DDX_ functions which are not very strict regarding their input. I have resolved that with scanf (or better _stscanf_s).

int nValue;
unsigned charsRead = 0;
const int fieldsRead = _stscanf_s(str, _T("%d%n"), &nValue, &charsRead);
if(fieldsRead == 1  &&  charsRead == _tcslen(str)) {
    // We have read all fields and we have read the complete string,
    // so str contains a valid pattern.
}

You can easily adjust that method if you want to read other types (e.g. "%u%n") or multiple values (e.g. "rate is: %d/%d Mbits/s%n"). Just don't forget to compare fieldsRead to the right value.

Upvotes: 1

Related Questions