Convert string to size_t

Is there a way to convert std::string to size_t ? The problem is that size_t is a platform dependent type (while this is the result of sizeof ). Therefore, I cannot guarantee that converting string to unsigned long or unsigned int will do it right.

EDIT: A simple case:

 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 
+7
c ++ string c ++ 11 size-t
source share
5 answers

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

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

+6
source share

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

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

Take a look here .

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

+6
source share

Suppose for a minute that size_t is a typedef for an existing integer, that is, the same width as unsigned int , unsigned long or unsigned long long .

AFAIR, it may be a separate (larger) type with respect to the standard wording, but I think this is unlikely.

Working with the assumption that size_t at most unsigned long long , stoull or strtoull , followed by clicking on size_t should work.


From the same assumption ( size_t , defined in terms of unsigned long or unsigned long long ), operator>> would be overloaded for this type.

+4
source share

you can use std::stringstream

 std::string string = "12345"; std::stringstream sstream(string); size_t result; sstream >> result; std::cout << result << std::endl; 
+3
source share
 #include <sstream> std::istringstream iss("a"); size_t size; iss >> size; 

Using iss.fail (), you check for an error. Instead of ("a") use the value you want to convert.

+1
source share

All Articles