转换字符串整数C中 [英] Converting string to integer C

查看:120
本文介绍了转换字符串整数C中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找出是否有将字符串转换在C整数的另一种方式。

I am trying to find out if there is an alternative way of converting string to integer in C.

我经常做我的code以下。

I regularly do the following in my code.

char s[] = "45";

int num = atoi(s);

那么,有没有一个短的路还是另辟蹊径?

So, is there a short way or another way?

推荐答案

与strtol 哪个更好海事组织。此外,我已采取 strtonum ,所以用它,如果你有(但请记住它不是便携式):

There is strtol which is better IMO. Also I have taken a liking in strtonum, so use it if you have it (but remember it's not portable):

long long
     strtonum(const char *nptr, long long minval, long long maxval,
     const char **errstr);

修改

您可能也有兴趣在 strtoumax strtoimax 这是C99的标准功能。例如,你可以说:

EDIT

You might also be interested in strtoumax and strtoimax which are standard functions in C99. For example you could say:

uintmax_t num = strtoumax(s, NULL, 10);
if (num == UINTMAX_MAX && errno == ERANGE)
    /* Could not convert. */

不管怎样,远离远的atoi

调用的atoi(STR)应等同于:

The call atoi(str) shall be equivalent to:

(int) strtol(str, (char **)NULL, 10)


  
  

除了使用错误的处理可能不同。 如果该值不能
  再presented,这种行为是未定义

这篇关于转换字符串整数C中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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