convert string to size_t

Let us assume for a minute that size_t is a typedef to an existing integer, i.e. the same width as either unsigned int, unsigned long, or unsigned long long.

AFAIR it could be a separate (larger still) type as far as the standard wording is concerned, but I consider that to be highly unlikely.

Working with that assumption that size_t is not larger than unsigned long long, either stoull or strtoull with subsequent cast to size_t should work.


From the same assumption (size_t defined in terms of either unsigned long or unsigned long long), there would be an operator>> overload for that type.


You can use %zd as the format specifier in a scanf-type approach.

Or use a std::stringstream which will have an overloaded >> to size_t.


You may want to use sscanf with the %zu specifier, which is for std::size_t.

sscanf(input.c_str(), "%zu", &index);

Have a look here.

Literally, I doubt that there is an overloaded operator >> of std::basic_istringstream for std::size_t. See here.


you can use std::stringstream

std::string string = "12345";
std::stringstream sstream(string);
size_t result;
sstream >> result;
std::cout << result << std::endl;