0

Hi Can anyone help me please. I need to check that my input only contains integers. Im guessing from looking it up that I use the isDigit function but I am not sure how to use this to check the whole number.

I'm using C++ to interact with MSI so i'm getting the integer as follows:

hr = WcaGetProperty(L"LOCKTYPE",&szLockType);
ExitOnFailure(hr, "failed to get the Lock Type");

I think i have to change szLockType to a char and then use isdigit to scan through each character but i am not sure how to implement this. Any help would be greatly appreciated. P.s im a beginner so please excuse if this is a really trivial question..:)

1

3 Answers 3

2

Use std::stoi(). You'll get an exception if the string is not an integer value.

Sign up to request clarification or add additional context in comments.

1 Comment

No, it won't check that the input is a valid integer, only that it has a non-whitespace prefix that is a valid integer, e.g: std::stoi(" 123broohaha ") will return 123, but std::stoi(" broohaha123 ") will throw.
0

What's the type of szLockType?

Is it a a null-terminated char-string?

Then you can use the array syntax to get individual characters.

for(int i = 0; i < std::strlen(szLockType); i++) {
    if(!std::isDigit(szLockType[i])) {
         // it contains a non-digit - do what you have to do and then...
         break; // ...to exit the for-loop
    }
}

Or is it a std::string? Then the syntax is slightly different:

for(int i = 0; i < szLockType.length(); i++) {
    if(!std::isDigit(szLockType.at(i)) {
         // it contains a non-digit - do what you have to do and then...
         break; // ...to exit the for-loop
    }
}

4 Comments

The value I am getting is a TCHAR* will this still work? I tried the first one and even converted it to a char but i wanted a char*.
Changed it so that is an int..:)
depending on the plattform, tchar is either a synonym for char (1-byte ASCII-characters) or for wchar (2-byte unicode-characters): msdn.microsoft.com/en-us/library/office/cc842072.aspx. The function to get the length of a wchar string is std::wcslen. The wchar version of isdigit is iswdigit.
Its windows..:) szLockType is now an int so il look into converting that. Thanks
0

Even better, with modern C++ you can do this:

#include <algorithm>
#include <cctype>

auto lambda = [](auto elem)
{
    return std::isdigit(elem);
};

return std::all_of(szLockType, szLockType + strlen(szLockType), lambda);

Your choice as to whether you prefer a named lambda or regular, anonymous lambda.

FYI it is std::isdigit rather than isDigit.

https://en.cppreference.com/w/cpp/string/byte/isdigit

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.