简体   繁体   中英

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

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 . Seehere .

Let us assume for a minute that size_t is a typedef to an existing integer, ie 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 .

#include <sstream>

std::istringstream iss("a");
size_t size;
iss >> size;

By using iss.fail(), you check failure. Instead of ("a"), use value you want to convert.

/**
   * @brief  Convert const char* to size_t
   * @note   When there is an error it returns the maximum of size_t
   * @param  *number: const char* 
   * @retval size_t
   */
  size_t to_size_t(const char *number) {
    size_t sizeT;
    std::istringstream iss(number);
    iss >> sizeT;
    if (iss.fail()) {
      return std::numeric_limits<size_t>::max();
    } else {
      return sizeT;
    }
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM