问题
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 float
s) and atol (for long
s)
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