If you have string input containing the value for size_t
and want to get the value, you can use sscanf()
with the %zu
format specifier to read the value and save it in the corresponding size_t
variable.
Note. Remember to check the success of sscanf()
and the family.
Pseudo Code:
size_t len = 0; if (1 == sscanf(input, "%zu", &len)) printf("len is %zu\n", len);
However, FWIW, this will not handle an overflow event. In case the input length is long enough for your program to process, you can use strtoumax()
and check for overflow, finally returning the return value of size_t
. See Mr. Blue Moon is an answer related to this.
However, if you don't mind a different approach, instead of accepting the input as sting and converting it to size_t
, you can directly accept the input as size_t
, for example
size_t arr_size = 0; scanf("%zu", &arr_size);
source share