user34537
user34537

Reputation:

why this conversion doesn't work?

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?

Upvotes: 1

Views: 605

Answers (4)

AProgrammer
AProgrammer

Reputation: 52284

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

Upvotes: 0

GManNickG
GManNickG

Reputation: 503865

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?

Upvotes: 2

Mark Ransom
Mark Ransom

Reputation: 308206

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

Upvotes: 3

sepp2k
sepp2k

Reputation: 370162

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.

Upvotes: 4

Related Questions