Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert string to size_t

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
like image 436
Humam Helfawi Avatar asked Dec 02 '15 13:12

Humam Helfawi


2 Answers

you can use std::stringstream

std::string string = "12345";
std::stringstream sstream(string);
size_t result;
sstream >> result;
std::cout << result << std::endl;
like image 149
Yuriy Orlov Avatar answered Oct 15 '22 04:10

Yuriy Orlov


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.

like image 22
Lingxi Avatar answered Oct 15 '22 04:10

Lingxi