dimanche 24 septembre 2017

Using Numeric limits gives the wrong answer during string conversion

I am using the following implementation for atoi and it seems to fail with std::int32_t when passed through a variable however it passes when I type the value directly any suggestions ?

template<typename t>
std::string mitoa(t num,int base=10)
{
    char str [sizeof(t)*8+1];
    int i = 0;
    bool isNegative = false;

    if (num == 0)
    {
        str[i++] = '0';
        str[i] = '\0';
        return str;
    }

    if (num < 0 && base == 10)
    {
        isNegative = true;
        num = -num;
    }

    // Process individual digits
    while (num != 0)
    {
        int rem = fmod(num,base);
        str[i++] = (rem > 9)? (rem-10) + 'a' : rem + '0';
        num = num/base;
    }

    if (isNegative)
        str[i++] = '-';

    str[i] = '\0';


    reverse(str, i);

    return str;
}

Now the following works fine

std::string val = mitoa(-2147483648);

However this is wrong

std::string val = mitoa(std::numeric_limits<std::int32_t>::min());

Any suggestions why second one is wrong ?

Aucun commentaire:

Enregistrer un commentaire