gcc 4.4.4 c89
What is better to convert a string to an integer value.
I have tried 2 different methods atoi and sscanf. Both work as expected.
char digits[3] = "34";
int device_num = 0;
if(sscanf(digits, "%d", &device_num) == EOF) {
fprintf(stderr, "WARNING: Incorrect value for device\n");
return FALSE;
}
or using atoi
device_num = atoi(digits);
I was thinking that the sscanf would be better as you can check for errors. However, atoi doesn’t doing any checking.
You have 3 choices:
atoiThis is probably the fastest if you’re using it in performance-critical code, but it does no error reporting. If the string does not begin with an integer, it will return 0. If the string contains junk after the integer, it will convert the initial part and ignore the rest. If the number is too big to fit in
int, the behaviour is unspecified.sscanfSome error reporting, and you have a lot of flexibility for what type to store (signed/unsigned versions of
char/short/int/long/long long/size_t/ptrdiff_t/intmax_t).The return value is the number of conversions that succeed, so scanning for
"%d"will return 0 if the string does not begin with an integer. You can use"%d%n"to store the index of the first character after the integer that’s read in another variable, and thereby check to see if the entire string was converted or if there’s junk afterwards. However, likeatoi, behaviour on integer overflow is unspecified.strtoland familyRobust error reporting, provided you set
errnoto 0 before making the call. Return values are specified on overflow anderrnowill be set. You can choose any number base from 2 to 36, or specify 0 as the base to auto-interpret leading0xand0as hex and octal, respectively. Choices of type to convert to are signed/unsigned versions oflong/long long/intmax_t.If you need a smaller type you can always store the result in a temporary
longorunsigned longvariable and check for overflow yourself.Since these functions take a pointer to pointer argument, you also get a pointer to the first character following the converted integer, for free, so you can tell if the entire string was an integer or parse subsequent data in the string if needed.
Personally, I would recommend the
strtolfamily for most purposes. If you’re doing something quick-and-dirty, atoi might meet your needs.As an aside, sometimes I find I need to parse numbers where leading whitespace, sign, etc. are not supposed to be accepted. In this case it’s pretty damn easy to roll your own for loop, eg.,
Or you can use (for robustness):