Convert string to short in C++

夙愿已清 提交于 2019-12-05 04:11:52

Basically, an std::stos function is missing for unknown reasons, but you can easily roll your own. Use std::stoi to convert to int, check value against short boundaries given by e.g. std::numeric_limits<short>, throw std::range_error if it's not in range, otherwise return that value. There.

If you already have the Boost library installed you might use boost::lexical_cast for convenience, but otherwise I would avoid it (mainly for the verbosity and library dependency, and it's also a little inefficient).

Earlier boost::lexical_cast was known for not being very efficient, I believe because it was based internally on stringstreams, but as reported in comments here the modern version is faster than conversion via stringstream, and for that matter than via scanf.

An efficient way is to use boost::lexical_cast:

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

You will need to install boost library and the following include: #include <boost/lexical_cast.hpp>

You should catch bad_lexical_cast in case the cast fails:

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

You can also use ssprintf with the %hi format specifier.

Example:

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

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

the number should never go above three or below zero

If you really really need to save memory, then this will also fit in a char (regardless whether char is signed or unsigned).

Another 'extreme' trick: if you can trust there are no weird things like "002" then what you have is a single character string. If that is the case, and you really really need performance, try:

char result = (char)( *ptr_c_string - '0' );
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!