1

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?

Artem Barger
  • 40,769
  • 9
  • 59
  • 81
  • Why do you expect it to return true? What are you expecting `!(ss >> std::ws).eof()` to evaluate to? or `(s >> v).fail()` for that matter? – CB Bailey Aug 07 '09 at 17:56
  • 3
    Step 1: Stop trying to be clever. Break up the expression so it is readable, you are not doing anybody any fovours. Especially yourself. Once you have it working with a set of unit tests then try your little optimization trick to see if it still works. – Martin York Aug 07 '09 at 18:05
  • 1
    Actually, I wrote that Martin. http://stackoverflow.com/questions/1243428/convert-string-to-int-with-bool-fail-in-c/1243435#1243435 – GManNickG Aug 07 '09 at 18:19
  • 1
    That is the std::stringstream version of boost::lexical_cast. – GManNickG Aug 07 '09 at 18:22

4 Answers4

4

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
  • 363,768
  • 54
  • 674
  • 675
3

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

Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
  • i completely missed that. I didnt understand streams enough and was rushing –  Aug 07 '09 at 19:50
2

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?

GManNickG
  • 494,350
  • 52
  • 494
  • 543
  • 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. –  Aug 07 '09 at 18:25
  • oops, i didnt explain yesterday post. I started it before i went to bed. I woke up 1hr ago. –  Aug 07 '09 at 18:27
0

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

AProgrammer
  • 51,233
  • 8
  • 91
  • 143