Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get size_t from string?

Tags:

c

string

size-t

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

like image 200
Alex Avatar asked Sep 01 '15 07:09

Alex


Video Answer


1 Answers

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);
like image 199
Sourav Ghosh Avatar answered Sep 28 '22 05:09

Sourav Ghosh