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?
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?
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 ...
.
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>
The atoi
function will convert from the string to an integer:
// requires including stdlib.h
int nr = atoi(str);