How do you get an unsigned long out of a string?

ぃ、小莉子 提交于 2019-12-03 15:50:09

One way to do it:

stringstream(str) >> ulongVariable;

You can use strtoul with no problem. The function returns an unsigned long. If convertion can not be performed the function return 0. If the correct long value is out of range the function return ULONG_MAX and the errno global variable is set to ERANGE.

template <class T>
T strToNum(const std::string &inputString,
           std::ios_base &(*f)(std::ios_base&) = std::dec)
{
    T t;
    std::istringstream stringStream(inputString);

    if ((stringStream >> f >> t).fail())
    {
        throw runtime_error("Invalid conversion");
    }
    return t;
}


// Example usage
unsigned long ulongValue = strToNum<unsigned long>(strValue);
int intValue             = strToNum<int>(strValue);

int intValueFromHex      = strToNum<int>(strHexValue,std::hex);
unsigned long ulOctValue = strToNum<unsigned long>(strOctVal, std::oct);

If you can use the boost libraries (www.boost.org) look at the conversion library - it's a header only include

#include "boost/lexical_cast.hpp"

then all you need to do is

unsigned long ul = boost::lexical_cast<unsigned long>(str);

Jeffrey Stedfast has a beautiful post about writing int parser routines for Mono (in C).
It generates code that uses uses native types (you need 32 bit to parse 32 bit) and error codes for overflow.

Use "atol" in-built std function

For example std::string input = "1024";

std::atol(input.c_str());

Atol expect parameter to be of type c string, so c_str() does it that for you.

Robust way will be write a static function and use it

bool str2Ulong(const string& str,unsigned long & arValue)
{
   char *tempptr=NULL;
   arValue=strtoul(str,tempptr,10);

   return ! (arValue==0 && tempptr==str.c_str());

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