How to get size_t from a string?

I need to get the size of an array from user input. It seemed to me natural to store the input as size_t , however, it was looking for a suitable strto...() function that I could not find. I just used strtoull() , since an unsigned long long guaranteed to be at least 64 bits, and I still use C99. 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 do not need the length of the string! The user enters the size of the large buffer as a string, for example, "109302393029" . I need to get this number and save it as size_t . Of course, I could use strtol() or even atoi() , but this seems like a clumsy hack ( size_t may contain larger values ​​than int , for example, and I want the user to be able to enter any value into the address space).

+3
source share
3 answers

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); 
+9
source

Just enter the input as unsigned int and put it in size_t or just:

 size_t length; scanf("%zu", &length); 
+2
source

You can use strtoumax() to do 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 because it helps detect overflow when specifying an arbitrarily large input.

The scanf() family functions cannot detect integer overflow, resulting in undefined behavior .

+2
source

Source: https://habr.com/ru/post/1014091/


All Articles