Get int value from string C [duplicate]

感情迁移 提交于 2020-01-02 14:31:31

问题


Given that I have the following:

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

I would like to get the number 1524 in 'nr'.

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


回答1:


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

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




回答2:


Use the atoi function:

nr = atoi(str);

There is also atof (for floats) and atol (for longs)

All of these functions are defined in <stdlib.h>.




回答3:


The standard library call is atoi(), though there's also strtol() which has a couple added features. 1) it lets you specify the numerical base (like base 10), and 2) it returns the pointer to the place in the string where it stopped parsing.

Both are defined in the header <stdlib.h>




回答4:


The atoi function will convert from the string to an integer:

// requires including stdlib.h

int nr = atoi(str);


来源:https://stackoverflow.com/questions/21244511/get-int-value-from-string-c

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