Convert string to short in C ++

So, I looked at how to convert a string to short and found a lot about how to convert a string to an integer. I would leave the question as a comment on these topics, but I do not have enough reputation. So what I want to do is convert the string to short, because the number should never exceed three or less than zero, and the shorts save memory (as far as I know).

To be clear, I do not mean ASCII codes.

Another thing I want to do is to check if the conversion of the string to short works, because I will use the string consisting of user input.

I know that I can do this with a while loop, but if in C ++ there is a built-in function that would be the same or more efficient than the while loop, I would really like to hear about it.

/ p>

+4
source share
4 answers

Basically, the function is std::stosmissing for unknown reasons, but you can easily collapse your own. Use std::stoito convert to int, check the value at the boundaries shortindicated, for example. std::numeric_limits<short>throw std::range_errorif it is not in the range, otherwise return this value. There.

​​ Boost, boost::lexical_cast , ( , , , ).

boost::lexical_cast , , , , , , , stringstream, , , scanf.

+8

- boost::lexical_cast:

short myShort = boost::lexical_cast<short>(myString);

, : #include <boost/lexical_cast.hpp>

bad_lexical_cast :

    try
    {
        short myShort = boost::lexical_cast<short>(myString);
    }
    catch(bad_lexical_cast &)
    {
        // Do something
    }
+2

ssprintf %hi.

:

short port;
char szPort[] = "80";

sscanf(szPort, "%hi", &port);
+1

, char ( , char ).

"" : , , "002", . , , :

char result = (char)( *ptr_c_string - '0' );
0

All Articles