Is there a way to convert std::string
to size_t
?
The problem is that size_t
is platform dependable type (while it is the result of the sizeof
). So, I can not guarantee that converting string
to unsigned long
or unsigned int
will do it correctly.
EDIT: A simple case is:
std::cout<< "Enter the index:";
std::string input;
std::cin >> input;
size_t index=string_to_size_t(input);
//Work with index to do something
you can use std::stringstream
std::string string = "12345";
std::stringstream sstream(string);
size_t result;
sstream >> result;
std::cout << result << std::endl;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With