在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)。