如何从字符串中获取unsigned long? [英] How do you get an unsigned long out of a string?

查看:194
本文介绍了如何从字符串中获取unsigned long?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++中从字符串中检索无符号长整数的最安全和最好的方法是什么?



我知道一些可能的方法。



首先,转换从atol签署的长。

  char * myStr; //以某种方式体验到某种价值。 
unsigned long n =((unsigned)atol(myStr));

这是一个明显的问题,当myStr中存储的值大于一个有符号long可以包含? atol检索是什么?



下一个可能是使用strtoul。

  char * myStr; //以某种方式体验到某种价值。 
unsigned long n = strtoul(myStr,0,10);

但是,这对我的需求来说有点过于复杂。我想要一个简单的函数,string in,unsigned long base 10 out。



我发现的最后一个可能性是使用sscanf。

  char * myStr; //以某种方式体验到某种价值。 
unsigned long n = 0;
if(sscanf(myStr,%lu,n)!= 1){
//做一些错误处理
}
pre>

同样,错误处理也是非常需要的,比我想要的更复杂一些。



剩下的明显的选择是写我自己的一个包装器围绕一个先前的可能性或一些事情循环通过字符串和手动转换每个数字,直到它达到ULONG_MAX。



我的问题是,我的google-fu找不到的其他选项是什么?在C ++ std库中,干净地将字符串转换为unsigned long并在失败时抛出异常的任何事情?



我的道歉,如果这是一个dupe,但我couldn'

解决方案

一种方法:

  stringstream(str)>> ulongVariable; 


What's the safest and best way to retrieve an unsigned long from a string in C++?

I know of a number of possible methods.

First, converting a signed long taken from atol.

char *myStr; // Initalized to some value somehow.
unsigned long n = ((unsigned)atol(myStr));

The obvious problem with this is, what happens when the value stored in myStr is larger than a signed long can contain? What does atol retrieve?

The next possibility is to use strtoul.

char *myStr; // Initalized to some value somehow.
unsigned long n = strtoul(myStr, 0, 10);

However, this is a little over complicated for my needs. I'd like a simple function, string in, unsigned long base 10 out. Also, the error handling leaves much to be desired.

The final possibility I have found is to use sscanf.

char *myStr; // Initalized to some value somehow.
unsigned long n = 0;
if(sscanf(myStr, "%lu", n) != 1) {
    //do some error handling
}

Again, error handling leaves much to be desired, and a little more complicated than I'd like.

The remaining obvious option is to write my own either a wrapper around one of the previous possibilities or some thing which cycles through the string and manually converts each digit until it reaches ULONG_MAX.

My question is, what are the other options that my google-fu has failed to find? Any thing in the C++ std library that will cleanly convert a string to an unsigned long and throw exceptions on failure?

My apologies if this is a dupe, but I couldn't find any questions that exactly matched mine.

解决方案

One way to do it:

stringstream(str) >> ulongVariable;

这篇关于如何从字符串中获取unsigned long?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆