Re: convert string to size_t



rtillmore@xxxxxxxxx writes:

On Nov 23, 9:30 pm, Peter Nilsson <ai...@xxxxxxxxxxx> wrote:
rtillm...@xxxxxxxxx wrote:
Hi,

There is a nice function called atoi that converts
strings to ints.

Better is strtol().

Is there a way to convert a string to size_t?

There is strtol and strtoul in C90, and additionally
strtoimax and strtoumax in C99. It's often better
to use the signed conversions since the unsigned
conversion don't capture errors in values that would
be outside the range of the result unsigned type.

--
Peter

It is best not to quote sigs.

Thanks for the information. My data will never be less
than zero so unsigned is good enough.

OK, but I worry that you may not have picked up on Peter Nilsson's
warning. Your (valid) data may never be less that zero, but you can't
easily check that this is the case using the unsigned strtou*
functions. For example, strtoul("-1", NULL, 0) returns ULONG_MAX
without any indication of an error. strtol will return -1 so you can
report an invalid input.

If by "my data will never be less than zero" you meant that you don't
need to check for negative data, then all is well, but I thought it
worth checking.

--
Ben.
.



Relevant Pages

  • Re: array of structures.
    ... strtol is for long (can also be used for int, ... short and signed char), strtoul is for unsigned long (also for unsigned ... wrong with the conversion, point you to the place where the conversion ...
    (comp.lang.c)
  • Re: [comp.lang.c.moderated] Re: reading in lines from a file that contain large (and unknown)
    ... After cursorily checking 7.19.6.2 "The fscanf function", ... referred 7.20.1.4 "The strtol, strtoll, strtoul, and strtoull ... functions", then the referred 6.4.4.1 "Integer constants", I think ...
    (comp.lang.c.moderated)
  • Re: scanning string for ![0..9]
    ... > This will only count leading non-digits. ... > A somewhat twisted method is to use strtol or strtoul in combination ... the conversion will detect and ...
    (comp.lang.c)
  • Re: strtoul bug (was Fibonacci number)
    ... "Richard Bos" wrote in message ... >> suffix that is interpreted as a negative sign by strtol(), ... >> recognized by strtoul(). ... OK, the suffix is recognized by strtoul, too, but doesn't affect its ...
    (comp.lang.c)