سؤال

I have created a wrapper around the .substr function:

wstring MidEx(wstring u, long uStartBased1, long uLenBased1)
{
    //Extracts a substring. It is fail-safe. In case we read beyond the string, it will just read as much as it has
    // For example when we read from the word HELLO , and we read from position 4, len 5000, it will just return LO
    if (uStartBased1 > 0)
    {
       if (uStartBased1 <= u.size())
        {
            return u.substr(uStartBased1-1, uLenBased1);
        }
    }
    return wstring(L"");
}

It works fine, however the compiler gives me the warning "<= Conflict between signed and unsigned".

Can somebody tell me how to do it correctly?

Thank you very much!

هل كانت مفيدة؟

المحلول

You should use wstring::size_type (or size_t) instead of long:

wstring MidEx(wstring u, wstring::size_type uStartBased1, wstring::size_type uLenBased1)
{
    //Extracts a substring. It is fail-safe. In case we read beyond the string, it will just read as much as it has
    // For example when we read from the word HELLO , and we read from position 4, len 5000, it will just return LO
    if (uStartBased1 > 0)
    {
       if (uStartBased1 <= u.size())
        {
            return u.substr(uStartBased1-1, uLenBased1);
        }
    }
    return wstring(L"");
}

which is the exact return type of u.size(). This way, you ensure that the comparision gives the expected result.

If you are working with std::wstring or another standard library container (like std::vector etc.), then x::size_type will be defined as size_t. So using it will be more consistent.

نصائح أخرى

You want unsigned arguments, something like:

wstring MidEx(wstring u, unsigned long uStartBased1, unsigned long uLenBased1)
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top