c++visual-c++iostreamstringstreamistream

stringstream operator>> fails to assign a number in debug


I have this simple function that, given a string str, if it is a number then return 'true' and overwrite the reference input num.

template <typename T>
bool toNumber(string str, T& num)
{
    bool bRet = false;
    if(str.length() > 0U)
    {
        if (str == "0")
        {
            num = static_cast<T>(0);
            bRet = true;
        }
        else
        {
            std::stringstream ss;
            ss << str;
            ss >> num;    // if str is not a number op>> it will assign 0 to num
            if (num == static_cast<T>(0)) 
            {
                bRet = false;
            }
            else
            {
                bRet = true;
            }
        }
    }
    else
    {
        bRet = false;
    }
    return bRet;
}

So I expect that:

int x, y;
toNumber("90", x); // return true and x is 90
toNumber("New York", y); // return false and let y unasigned.

On my machine, both debug and release configurations works fine, but on the server, only with the debug configuration, in calls like toNumber("New York", y) the 'ss >> num' fails to recognize that str is a string.

I checked the project configuration, but they are the same for both machines (the server is a svn-checkout of my local vs-2015 project).

I have literally no idea on how to solve the problem. Can anyone help me with this?


Solution

  • Your code is made too complicated, you can simplify it to this:

    template <typename T>
    bool toNumber(std::string str, T& num)
    {
        return !!(std::istringstream { std::move(str) } >> num);
    }
    

    https://godbolt.org/z/Pq5xGdof5

    Ok I've missed that you wish to avoid zero assignment in case of failure (what streams do by default):

    template <typename T>
    bool toNumber(std::string str, T& num)
    {
        T tmp;
        std::istringstream stream{ std::move(str) };
        if (stream >> tmp) {
            num = tmp;
        }
        return !!stream;
    }
    

    https://godbolt.org/z/nErqn3YYG