views:

348

answers:

4

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?

+4  A: 

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.

sepp2k
+2  A: 

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

Mark Ransom
i completely missed that. I didnt understand streams enough and was rushing
acidzombie24
+1  A: 

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?

GMan
Yes :D. My stream knowledge is poor and i am in the middle of homework that is due in 2hrs (i have 4 hrs to do it, i was absent). I rather ask how to properly convert an int then write a poor version myself.
acidzombie24
oops, i didnt explain yesterday post. I started it before i went to bed. I woke up 1hr ago.
acidzombie24
oh and thanks again for both of these answers :D
acidzombie24
A: 

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

AProgrammer