convert string to size_t

Humam Helfawi picture Humam Helfawi · Dec 2, 2015 · Viewed 23.7k times · Source

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

Answer

Yuriy Orlov picture Yuriy Orlov · Dec 2, 2015

you can use std::stringstream

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