C++ stoll對(duì)溢出是如何處理的

c++
小樊
106
2024-07-08 17:27:14
欄目: 編程語言

在C++中,std::stoll函數(shù)用于將字符串轉(zhuǎn)換為長(zhǎng)整型數(shù)值。當(dāng)使用std::stoll進(jìn)行轉(zhuǎn)換時(shí),如果字符串表示的數(shù)值超出了長(zhǎng)整型的范圍,即溢出了,std::out_of_range異常會(huì)被拋出。

例如,如果嘗試將一個(gè)超出long long的范圍的字符串轉(zhuǎn)換為長(zhǎng)整型數(shù)值,會(huì)拋出std::out_of_range異常:

#include <iostream>
#include <string>

int main() {
    std::string str = "12345678901234567890"; // 超出long long范圍
    try {
        long long num = std::stoll(str);
        std::cout << "Number: " << num << std::endl;
    } catch (const std::out_of_range& e) {
        std::cerr << "Error: " << e.what() << std::endl;
    }
    
    return 0;
}

在上面的代碼中,由于字符串表示的數(shù)值超出了long long的范圍,std::out_of_range異常會(huì)被捕獲并輸出錯(cuò)誤信息。因此,要注意在使用std::stoll進(jìn)行字符串轉(zhuǎn)換時(shí),確保輸入的字符串在目標(biāo)數(shù)據(jù)類型的范圍內(nèi)。

0