2

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?

Dragos Rizescu
  • 3,380
  • 5
  • 31
  • 42

4 Answers4

9

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

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
5

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

Linuxios
  • 34,849
  • 13
  • 91
  • 116
4

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>

woolstar
  • 5,063
  • 20
  • 31
3

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

// requires including stdlib.h

int nr = atoi(str);
Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373