1

In C# there are try functions to avoid exceptions e.g. Int.TryParse(). I am looking for a similar function for C++ as a replacement for std::stoi().

Werner
  • 281
  • 1
  • 12
  • 1
    Do you want to be able to catch the exception? – Carl Mar 16 '18 at 16:18
  • you can use [this](https://stackoverflow.com/questions/36492029/c-function-call-wrapper-with-function-as-template-argument) to wrap calls to any function and return false if you catch exception – Krzysztof Skowronek Mar 16 '18 at 16:20
  • 2
    Use a function like strtol(). –  Mar 16 '18 at 16:21
  • If you want to avoid exceptions test first: https://stackoverflow.com/questions/437882/what-is-the-c-sharp-equivalent-of-nan-or-isnumeric – Jay Mar 16 '18 at 16:21
  • @Carl: no I want to avoid id, e.g. in case of an empty string it should return 0 an not throw an exception. – Werner Mar 16 '18 at 16:38
  • 1
    I use the C++ versions of the good ol C `strto` family of functions. [Here's documentation for one of them](http://en.cppreference.com/w/cpp/string/byte/strtol). The rest are linked at the bottom of the page just below the usage example. – user4581301 Mar 16 '18 at 16:49
  • @Neil: thanks, you are right, I failed to see that strtol never throws an exception but std:stol does. However is there also a similar std function ? – Werner Mar 16 '18 at 16:51
  • strtol is part of the standard library –  Mar 16 '18 at 16:52

1 Answers1

1

C++ like way:

unsigned long value;
std::istringstream s(data);
if(s >> value)
{
     // possibly check, if the stream was consumed entirely...
}

What I like about this approach: if using cstdint's types, you do not need to worry about if you use the correct type with the correct function...

Aconcagua
  • 24,880
  • 4
  • 34
  • 59