An exception-less wrapper for std::stoi

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP











up vote
1
down vote

favorite












std::stoi may throw exceptions so it needs to be surrounded by try/catch.



In applications where std::stoi may be used frequently, it could be useful to have a wrapper.



Is this good practice?



int _stoi(std::string str, int* p_value) 
// wrapping std::stoi because it may throw an exception

try
*p_value = std::stoi(str);
return 0;


catch (const std::invalid_argument& ia)
//std::cerr << "Invalid argument: " << ia.what() << std::endl;
return -1;


catch (const std::out_of_range& oor)
//std::cerr << "Out of Range error: " << oor.what() << std::endl;
return -2;


catch (const std::exception& e)

//std::cerr << "Undefined error: " << e.what() << std::endl;
return -3;











share|improve this question









New contributor




Sparkler is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.



















  • std::strtol addresses the problem in a much cleaner way.
    – vnp
    2 hours ago














up vote
1
down vote

favorite












std::stoi may throw exceptions so it needs to be surrounded by try/catch.



In applications where std::stoi may be used frequently, it could be useful to have a wrapper.



Is this good practice?



int _stoi(std::string str, int* p_value) 
// wrapping std::stoi because it may throw an exception

try
*p_value = std::stoi(str);
return 0;


catch (const std::invalid_argument& ia)
//std::cerr << "Invalid argument: " << ia.what() << std::endl;
return -1;


catch (const std::out_of_range& oor)
//std::cerr << "Out of Range error: " << oor.what() << std::endl;
return -2;


catch (const std::exception& e)

//std::cerr << "Undefined error: " << e.what() << std::endl;
return -3;











share|improve this question









New contributor




Sparkler is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.



















  • std::strtol addresses the problem in a much cleaner way.
    – vnp
    2 hours ago












up vote
1
down vote

favorite









up vote
1
down vote

favorite











std::stoi may throw exceptions so it needs to be surrounded by try/catch.



In applications where std::stoi may be used frequently, it could be useful to have a wrapper.



Is this good practice?



int _stoi(std::string str, int* p_value) 
// wrapping std::stoi because it may throw an exception

try
*p_value = std::stoi(str);
return 0;


catch (const std::invalid_argument& ia)
//std::cerr << "Invalid argument: " << ia.what() << std::endl;
return -1;


catch (const std::out_of_range& oor)
//std::cerr << "Out of Range error: " << oor.what() << std::endl;
return -2;


catch (const std::exception& e)

//std::cerr << "Undefined error: " << e.what() << std::endl;
return -3;











share|improve this question









New contributor




Sparkler is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











std::stoi may throw exceptions so it needs to be surrounded by try/catch.



In applications where std::stoi may be used frequently, it could be useful to have a wrapper.



Is this good practice?



int _stoi(std::string str, int* p_value) 
// wrapping std::stoi because it may throw an exception

try
*p_value = std::stoi(str);
return 0;


catch (const std::invalid_argument& ia)
//std::cerr << "Invalid argument: " << ia.what() << std::endl;
return -1;


catch (const std::out_of_range& oor)
//std::cerr << "Out of Range error: " << oor.what() << std::endl;
return -2;


catch (const std::exception& e)

//std::cerr << "Undefined error: " << e.what() << std::endl;
return -3;








c++ parsing error-handling integer wrapper






share|improve this question









New contributor




Sparkler is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











share|improve this question









New contributor




Sparkler is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









share|improve this question




share|improve this question








edited 1 hour ago









200_success

126k14147408




126k14147408






New contributor




Sparkler is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









asked 4 hours ago









Sparkler

1061




1061




New contributor




Sparkler is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.





New contributor





Sparkler is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






Sparkler is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











  • std::strtol addresses the problem in a much cleaner way.
    – vnp
    2 hours ago
















  • std::strtol addresses the problem in a much cleaner way.
    – vnp
    2 hours ago















std::strtol addresses the problem in a much cleaner way.
– vnp
2 hours ago




std::strtol addresses the problem in a much cleaner way.
– vnp
2 hours ago










2 Answers
2






active

oldest

votes

















up vote
2
down vote













This wrapper effectively removes some of the available functionality from std::stoi() because its signature is



int stoi(const std::string& str, std::size_t* pos = 0, int base = 10);


Because your wrapper does not allow a pos or base argument you cannot use it to give you the number of characters processed (with pos) nor to convert using a different base. std::stoi() provides default values for these arguments so you'd only have to provide them if you need the non-default behavior.



Also, you don't take the std::string argument by const reference like std::stoi() -- the string argument is probably not too expensive to copy in this context but why not accept the argument the same way std::stoi() does?



For completeness, I would also implement the overload of std::stoi() which accepts a std::wstring (and possibly std::stol() and std::stoll().



I would also avoid the leading underscore, as identifiers with a leading underscore are reserved.



With these suggestions the wrapper would be implemented as



int stoi(const std::string& str, int* p_value, std::size_t* pos = 0, int base = 10) 
// wrapping std::stoi because it may throw an exception

try
*p_value = std::stoi(str, pos, base);
return 0;


catch (const std::invalid_argument& ia)
//std::cerr << "Invalid argument: " << ia.what() << std::endl;
return -1;


catch (const std::out_of_range& oor)
//std::cerr << "Out of Range error: " << oor.what() << std::endl;
return -2;


catch (const std::exception& e)

//std::cerr << "Undefined error: " << e.what() << std::endl;
return -3;







share|improve this answer





























    up vote
    1
    down vote













    int _stoi(std::string str, int* p_value) {


    Identifiers that begins with an underscore is reserved to the implementation for use as a name in the global namespace.



    I would expect the signature of your _stoi to match that of the std::stoi you are wrapping. So you should take the std::string by reference-to-const, take an in-out parameter to indicate how much of str was processed, and the base you are converting to.




     try 
    *p_value = std::stoi(str);
    return 0;

    catch (...)
    return -3;



    Instead of returning integers that represent error-codes, leverage the type-system. There are a class of types called "either" types that let you return a result or an enumerated error. There are also variant types that let you return one of multiple types of return or error values.



    If you plan on supporting the full set of std::stoX family of functions and their overloads between std::string and std::wstring, I urge you to look at lippincott functions as well as variadic argument passing.






    share|improve this answer




















      Your Answer





      StackExchange.ifUsing("editor", function ()
      return StackExchange.using("mathjaxEditing", function ()
      StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix)
      StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
      );
      );
      , "mathjax-editing");

      StackExchange.ifUsing("editor", function ()
      StackExchange.using("externalEditor", function ()
      StackExchange.using("snippets", function ()
      StackExchange.snippets.init();
      );
      );
      , "code-snippets");

      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "196"
      ;
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function()
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled)
      StackExchange.using("snippets", function()
      createEditor();
      );

      else
      createEditor();

      );

      function createEditor()
      StackExchange.prepareEditor(
      heartbeatType: 'answer',
      convertImagesToLinks: false,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: null,
      bindNavPrevention: true,
      postfix: "",
      imageUploader:
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      ,
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      );



      );






      Sparkler is a new contributor. Be nice, and check out our Code of Conduct.









       

      draft saved


      draft discarded


















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f206754%2fan-exception-less-wrapper-for-stdstoi%23new-answer', 'question_page');

      );

      Post as a guest






























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes








      up vote
      2
      down vote













      This wrapper effectively removes some of the available functionality from std::stoi() because its signature is



      int stoi(const std::string& str, std::size_t* pos = 0, int base = 10);


      Because your wrapper does not allow a pos or base argument you cannot use it to give you the number of characters processed (with pos) nor to convert using a different base. std::stoi() provides default values for these arguments so you'd only have to provide them if you need the non-default behavior.



      Also, you don't take the std::string argument by const reference like std::stoi() -- the string argument is probably not too expensive to copy in this context but why not accept the argument the same way std::stoi() does?



      For completeness, I would also implement the overload of std::stoi() which accepts a std::wstring (and possibly std::stol() and std::stoll().



      I would also avoid the leading underscore, as identifiers with a leading underscore are reserved.



      With these suggestions the wrapper would be implemented as



      int stoi(const std::string& str, int* p_value, std::size_t* pos = 0, int base = 10) 
      // wrapping std::stoi because it may throw an exception

      try
      *p_value = std::stoi(str, pos, base);
      return 0;


      catch (const std::invalid_argument& ia)
      //std::cerr << "Invalid argument: " << ia.what() << std::endl;
      return -1;


      catch (const std::out_of_range& oor)
      //std::cerr << "Out of Range error: " << oor.what() << std::endl;
      return -2;


      catch (const std::exception& e)

      //std::cerr << "Undefined error: " << e.what() << std::endl;
      return -3;







      share|improve this answer


























        up vote
        2
        down vote













        This wrapper effectively removes some of the available functionality from std::stoi() because its signature is



        int stoi(const std::string& str, std::size_t* pos = 0, int base = 10);


        Because your wrapper does not allow a pos or base argument you cannot use it to give you the number of characters processed (with pos) nor to convert using a different base. std::stoi() provides default values for these arguments so you'd only have to provide them if you need the non-default behavior.



        Also, you don't take the std::string argument by const reference like std::stoi() -- the string argument is probably not too expensive to copy in this context but why not accept the argument the same way std::stoi() does?



        For completeness, I would also implement the overload of std::stoi() which accepts a std::wstring (and possibly std::stol() and std::stoll().



        I would also avoid the leading underscore, as identifiers with a leading underscore are reserved.



        With these suggestions the wrapper would be implemented as



        int stoi(const std::string& str, int* p_value, std::size_t* pos = 0, int base = 10) 
        // wrapping std::stoi because it may throw an exception

        try
        *p_value = std::stoi(str, pos, base);
        return 0;


        catch (const std::invalid_argument& ia)
        //std::cerr << "Invalid argument: " << ia.what() << std::endl;
        return -1;


        catch (const std::out_of_range& oor)
        //std::cerr << "Out of Range error: " << oor.what() << std::endl;
        return -2;


        catch (const std::exception& e)

        //std::cerr << "Undefined error: " << e.what() << std::endl;
        return -3;







        share|improve this answer
























          up vote
          2
          down vote










          up vote
          2
          down vote









          This wrapper effectively removes some of the available functionality from std::stoi() because its signature is



          int stoi(const std::string& str, std::size_t* pos = 0, int base = 10);


          Because your wrapper does not allow a pos or base argument you cannot use it to give you the number of characters processed (with pos) nor to convert using a different base. std::stoi() provides default values for these arguments so you'd only have to provide them if you need the non-default behavior.



          Also, you don't take the std::string argument by const reference like std::stoi() -- the string argument is probably not too expensive to copy in this context but why not accept the argument the same way std::stoi() does?



          For completeness, I would also implement the overload of std::stoi() which accepts a std::wstring (and possibly std::stol() and std::stoll().



          I would also avoid the leading underscore, as identifiers with a leading underscore are reserved.



          With these suggestions the wrapper would be implemented as



          int stoi(const std::string& str, int* p_value, std::size_t* pos = 0, int base = 10) 
          // wrapping std::stoi because it may throw an exception

          try
          *p_value = std::stoi(str, pos, base);
          return 0;


          catch (const std::invalid_argument& ia)
          //std::cerr << "Invalid argument: " << ia.what() << std::endl;
          return -1;


          catch (const std::out_of_range& oor)
          //std::cerr << "Out of Range error: " << oor.what() << std::endl;
          return -2;


          catch (const std::exception& e)

          //std::cerr << "Undefined error: " << e.what() << std::endl;
          return -3;







          share|improve this answer














          This wrapper effectively removes some of the available functionality from std::stoi() because its signature is



          int stoi(const std::string& str, std::size_t* pos = 0, int base = 10);


          Because your wrapper does not allow a pos or base argument you cannot use it to give you the number of characters processed (with pos) nor to convert using a different base. std::stoi() provides default values for these arguments so you'd only have to provide them if you need the non-default behavior.



          Also, you don't take the std::string argument by const reference like std::stoi() -- the string argument is probably not too expensive to copy in this context but why not accept the argument the same way std::stoi() does?



          For completeness, I would also implement the overload of std::stoi() which accepts a std::wstring (and possibly std::stol() and std::stoll().



          I would also avoid the leading underscore, as identifiers with a leading underscore are reserved.



          With these suggestions the wrapper would be implemented as



          int stoi(const std::string& str, int* p_value, std::size_t* pos = 0, int base = 10) 
          // wrapping std::stoi because it may throw an exception

          try
          *p_value = std::stoi(str, pos, base);
          return 0;


          catch (const std::invalid_argument& ia)
          //std::cerr << "Invalid argument: " << ia.what() << std::endl;
          return -1;


          catch (const std::out_of_range& oor)
          //std::cerr << "Out of Range error: " << oor.what() << std::endl;
          return -2;


          catch (const std::exception& e)

          //std::cerr << "Undefined error: " << e.what() << std::endl;
          return -3;








          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited 3 hours ago

























          answered 3 hours ago









          Null

          9032920




          9032920






















              up vote
              1
              down vote













              int _stoi(std::string str, int* p_value) {


              Identifiers that begins with an underscore is reserved to the implementation for use as a name in the global namespace.



              I would expect the signature of your _stoi to match that of the std::stoi you are wrapping. So you should take the std::string by reference-to-const, take an in-out parameter to indicate how much of str was processed, and the base you are converting to.




               try 
              *p_value = std::stoi(str);
              return 0;

              catch (...)
              return -3;



              Instead of returning integers that represent error-codes, leverage the type-system. There are a class of types called "either" types that let you return a result or an enumerated error. There are also variant types that let you return one of multiple types of return or error values.



              If you plan on supporting the full set of std::stoX family of functions and their overloads between std::string and std::wstring, I urge you to look at lippincott functions as well as variadic argument passing.






              share|improve this answer
























                up vote
                1
                down vote













                int _stoi(std::string str, int* p_value) {


                Identifiers that begins with an underscore is reserved to the implementation for use as a name in the global namespace.



                I would expect the signature of your _stoi to match that of the std::stoi you are wrapping. So you should take the std::string by reference-to-const, take an in-out parameter to indicate how much of str was processed, and the base you are converting to.




                 try 
                *p_value = std::stoi(str);
                return 0;

                catch (...)
                return -3;



                Instead of returning integers that represent error-codes, leverage the type-system. There are a class of types called "either" types that let you return a result or an enumerated error. There are also variant types that let you return one of multiple types of return or error values.



                If you plan on supporting the full set of std::stoX family of functions and their overloads between std::string and std::wstring, I urge you to look at lippincott functions as well as variadic argument passing.






                share|improve this answer






















                  up vote
                  1
                  down vote










                  up vote
                  1
                  down vote









                  int _stoi(std::string str, int* p_value) {


                  Identifiers that begins with an underscore is reserved to the implementation for use as a name in the global namespace.



                  I would expect the signature of your _stoi to match that of the std::stoi you are wrapping. So you should take the std::string by reference-to-const, take an in-out parameter to indicate how much of str was processed, and the base you are converting to.




                   try 
                  *p_value = std::stoi(str);
                  return 0;

                  catch (...)
                  return -3;



                  Instead of returning integers that represent error-codes, leverage the type-system. There are a class of types called "either" types that let you return a result or an enumerated error. There are also variant types that let you return one of multiple types of return or error values.



                  If you plan on supporting the full set of std::stoX family of functions and their overloads between std::string and std::wstring, I urge you to look at lippincott functions as well as variadic argument passing.






                  share|improve this answer












                  int _stoi(std::string str, int* p_value) {


                  Identifiers that begins with an underscore is reserved to the implementation for use as a name in the global namespace.



                  I would expect the signature of your _stoi to match that of the std::stoi you are wrapping. So you should take the std::string by reference-to-const, take an in-out parameter to indicate how much of str was processed, and the base you are converting to.




                   try 
                  *p_value = std::stoi(str);
                  return 0;

                  catch (...)
                  return -3;



                  Instead of returning integers that represent error-codes, leverage the type-system. There are a class of types called "either" types that let you return a result or an enumerated error. There are also variant types that let you return one of multiple types of return or error values.



                  If you plan on supporting the full set of std::stoX family of functions and their overloads between std::string and std::wstring, I urge you to look at lippincott functions as well as variadic argument passing.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered 3 hours ago









                  Snowhawk

                  4,69911027




                  4,69911027




















                      Sparkler is a new contributor. Be nice, and check out our Code of Conduct.









                       

                      draft saved


                      draft discarded


















                      Sparkler is a new contributor. Be nice, and check out our Code of Conduct.












                      Sparkler is a new contributor. Be nice, and check out our Code of Conduct.











                      Sparkler is a new contributor. Be nice, and check out our Code of Conduct.













                       


                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f206754%2fan-exception-less-wrapper-for-stdstoi%23new-answer', 'question_page');

                      );

                      Post as a guest













































































                      Comments

                      Popular posts from this blog

                      Long meetings (6-7 hours a day): Being “babysat” by supervisor

                      Is the Concept of Multiple Fantasy Races Scientifically Flawed? [closed]

                      Confectionery