Reputation:
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
Reputation: 52284
If you where expecting that stream IO would handle C++ comment as white space, that isn't the case.
Upvotes: 0
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
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