得到字符串C int值 [英] Get int value from string C

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

问题描述

由于我有以下几点:

char str[] = "1524";
int nr;

我想获得数 1524 在NR。

什么是实现,在C的最佳方式?

What's the best way to achieve that in C?

推荐答案

与错误检测的最好的是与strtol()

The best with error detection is strtol()

#include <errno.h>
#include <stdlib.h>

char str[] = "1524";
char *endptr;
errno = 0;
long l = strtol(str, &endptr, 10);
if (errno || *endptr != '\0' || str == endptr || l < INT_MIN || l > INT_MAX) {
  Handle_Error();
}
else {
  nr = l;
}

错误号变为非零时,上/下溢。结果
* endptr!='\\ 0'检测末多余的垃圾。结果
海峡!= endptr 检测到的字符串如。结果
比较对 INT_MAX INT_MIN 在需要时 INT 的范围有所不同。结果
也许更好的事情可做如果(错误== ERANGE ...

errno becomes non-zero when over/underflow occurs.
*endptr != '\0' detects extra garbage at the end.
str != endptr detects a strings like "".
Compare against INT_MAX, INT_MIN needed when int and long differ in range.
Maybe better to do if (errno == ERANGE ....

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

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