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

I regularly pattern the following in my code.

char s[] = "45";

int num = atoi(s);

So, is there a better way or another way?

推荐答案

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);

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. */

Anyway, stay away from atoi:

The call atoi(str) shall be equivalent to:

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

except that the handling of errors may differ. If the value cannot be represented, the behavior is undefined.

C++相关问答推荐

C/C++中的状态库

来自stdarg.h的c中的va_args无法正常工作<>

返回一个包含数组的 struct

将指针作为参数传递给函数

减法运算结果的平方的最快方法?

为什么C语言允许你使用var =(struct NAME){

如何在C中使printf不刷新标准输出?

将数据移动到寄存器时出现分段故障

循环中的静态变量与块中的变量和循环

如何读取程序中嵌入的数据S自己的ELF?

Fscanf打印除退出C代码为1的程序外的所有内容

问题:C#Define上的初始值设定项元素不是常量

当我在34mb的.mp4文件中使用FREAD时,我得到了一个分段错误,我如何解决它?

OMP并行嵌套循环

区分MySQL C界面中的文本和BLOB字段

未为同一文件中的函数执行DirectFunctionCall

我错误地修复了一个错误,想了解原因

与指针的原始C数组或C++向量<;向量<;双>>;

使用fread()函数读取txt文件

如何确保 gcc + libc 对于多字节字符串使用 UTF-8,对于 wchar_t 使用 UTF-32?