我在.substr函数周围创建了一个包装器:
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"");
}
它工作正常,但编译器给我警告“&lt; =有符号和无符号之间的冲突”。
有人可以告诉我如何正确地做到这一点吗?
非常感谢!
答案 0 :(得分:4)
您应该使用wstring::size_type
(或size_t
)代替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"");
}
这是u.size()
的确切返回类型。这样,您可以确保比较得到预期的结果。
如果您正在使用std::wstring
或其他标准库容器(例如std::vector
等),则x::size_type
将被定义为size_t
。所以使用它会更加一致。
答案 1 :(得分:0)
您需要unsigned
个参数,例如:
wstring MidEx(wstring u, unsigned long uStartBased1, unsigned long uLenBased1)