簡體   English   中英

將std :: string(保證數字)轉換為unsigned char

[英]Cast std::string (guaranteed numeric) to an unsigned char

我已經為鑄造字符串創建了一個模板來執行不同的數據類型,並且當數據類型是unsigned char時它會出現問題。

template<class TYPE>
bool TryParse(const std::string value, TYPE &out)
{
    std::istringstream iss(value);
    iss >> out;

    if (iss.fail())
    {
        return false;
    }

    return true;
}

問題是istringstream會將它看到的第一個字符視為char,而不是將其視為數字字符串。 因此,如果我傳遞值“255”,則返回的值將為“2”。

最好的解決方案是將out變量作為unsigned int轉換,執行操作,然后再次強制轉換?

我建議有一個特別適用於unsigned char情況的重載,因為你需要使用一個中間類型。

bool TryParse(const std::string & value, unsigned char & out)
{
    std::istringstream iss(value);
    unsigned int i;
    iss >> i;

    if (iss.fail()) { return false; }

    // The less-than-min check is technically redundant because both i and out
    // are unsigned, but it makes me feel better having it there.  It will become
    // necessary for the "signed char" overload, anyway.
    if (i > std::numeric_limits<unsigned char>::max() ||
        i < std::numeric_limits<unsigned char>::min()) {
            throw std::overflow_error();
            // Or you could "return false" instead, if that makes more sense.
    }

    out = static_cast<unsigned char>(i);
    return true;
}

您可以對signed char使用幾乎相同的函數。 (只需更換每一個unsignedsigned 。)

我不建議在模板中使用中間類型,因為您需要使用盡可能廣泛的類型,並且沒有任何一種類型可以使用。 unsigned long long intsigned long long int不兼容,反之亦然 - 這些類型都不兼容floatdouble 擁有一個直接使用所請求類型的基本模板,對於有問題的類型(例如char )的重載是正確的方法。


請注意,我已將value參數更改為對const字符串的引用,因為這意味着調用者無需無理由地復制字符串。 我建議你也改變你的模板功能。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM