Question

Below is my func. I call it with

if(try_strtol(v, rhs))

and RHS = "15\t// comment"

bool try_strtol(int64_t &v, const string& s)
{
    try
    {
        std::stringstream ss(s);
        if ((ss >> v).fail() || !(ss >> std::ws).eof())
            throw std::bad_cast();
        return true;
    }
    catch(...)
    {
        return false;
    }
}

It returns false, i except true with v=15. How do i fix this?

Was it helpful?

Solution

If you want it to return a boolean, just do this:

bool try_strtol(int64_t &v, const string& s)
{
    std::stringstream ss(s);
    return (ss >> v).fail() || !(ss >> std::ws).eof();
}

And it's failing because it's a bad cast. Were you hoping the comment would be ignored?

OTHER TIPS

Why do you expect (ss >> std::ws).eof() to be true? rhs contains non-whitespace characters after 15, so the if condition will be true and the exception will be thrown, which is why it returns false.

After std::ws skips the tab, you aren't at eof yet.

If you where expecting that stream IO would handle C++ comment as white space, that isn't the case.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top