20 Şubat 2020 Perşembe

String'i Integer'a Çevirme - C++

Giriş
C++'ta string'i sayısal bir değere çevirmek için şu metodlar mevcut. Bu metodlar template değiller. Her tip için farklı bir metod tanımlı
stoi
stol
stoll
stoul
stoull
stof
stod
stold
C++17 ile gelen std::from_chars() metodu da template değil ancak farklı sayısal tipler ile çalışabilecek şekilde overload edilmiş.

Boost
Eğer istenirse boost::lexical_cast() metodu da kolaylıkla kullanılabilir.

std::stoi - std::string alır ve int'e çevirir
std::stoi yazısına taşıdım.

std::stol metodu
Örnek ver

std::stoll metodu
Örnek ver

std::stoul metodu
Örnek ver

std::stoull metodu
Örnek ver

std::stof metodu
Örnek ver

std::stod - std::string alır ve double'a çevirir
std::stod yazısına taşıdım.

std::stold metodu
Örnek ver

std::from_chars metodu
C++17 ile geliyor. char * ile çalışır.
Örnek
Şöyle yaparız.
double dbl;
auto result = std::from_chars(&value_str[0], &value_str[0] + value_str.size(), dbl);
Örnek
Şöyle yaparız
template<typename Numeric>
void stuff(std::string_view s) {
  auto value = Numeric{};

  auto [ptr, error_code] = std::from_chars(s.data(), s.data() + s.size(), value);

  if (error_code == std::errc{}) {
    // converion successful, do something with value
  }
}
istringstream
Bir diğer yöntem ise istringstream akımını kullanmak. Örnek:
std::istringstream parser( line.substr( 54, 3 ) );
parser >> i;
if ( !parser || parser.get() != EOF ) {
    //  Error.
} else {
    //  No error, you can use i...
}



Hiç yorum yok:

Yorum Gönder