问题
I need to get an array size from user input. It seemed natural to me to store the input as size_t
, however looking for an appropriate strto...()
function I couldn't find any. I just used strtoull()
, since unsigned long long
is guaranteed to be at least 64 bits and I'm using C99 anyway. But I was wondering what would be the best way to get size_t
from a string - say, in ANSI C.
Edit:
To clarify, I don't want the string length! The user will input the size of a large buffer in the form of a string, for instance "109302393029"
. I need to get that number and store as size_t
. Of course I could use strtol()
or even atoi()
, but it seems like a clumsy hack (size_t
may hold larger values than int
, for instance, and I want the user to be able to input any value in the addressable space).
回答1:
In case you have a string input containing the value for a size_t
and you want to get the value, you can use sscanf() with %zu
format specifier to read the value and store it into corresponding size_t
variable.
Note: do not forget to check the success of sscanf()
and family.
Pseudo-code:
size_t len = 0;
if (1 == sscanf(input, "%zu", &len))
printf("len is %zu\n", len);
However, FWIW, this won't handle the overflow case. In case of the input length being arbitaryly large which your program should be able to handle, you may want to make use of strtoumax() and check for overflow, finally casting the returned value to size_t
. Please see Mr. Blue Moon's answer related to this.
However, if you don't mind another approach, instead of taking the input as sting and converting it to size_t
, you can directly take the input as size_t
, like
size_t arr_size = 0;
scanf("%zu", &arr_size);
回答2:
You can use strtoumax() to perform the conversion:
#include <inttypes.h>
intmax_t strtoimax(const char *nptr, char **endptr, int base);
uintmax_t strtoumax(const char *nptr, char **endptr, int base);
and cast the result to size_t. This is a better approach since it helps detect overflow when arbitrarily large input is given.
The scanf()
family functions can't detect integer overflow, which results in undefined behaviour.
回答3:
Just get the input as unsigned int and cast it to size_t, or just:
size_t length;
scanf("%zu", &length);
来源:https://stackoverflow.com/questions/32325479/how-to-get-size-t-from-string