2015-02-09 64 views
3

使用std :: setbase格式化數字以將int的數字最小值傳遞給std :: stoi拋出std :: out_of_range異常,但我不懂爲什麼。如果有人能幫助我更好地理解異常背後的原因,我將不勝感激。std :: stoi,std :: setbase和std :: out_of_range錯誤

代碼段:

#include <iomanip> 
#include <iostream> 
#include <limits> 
#include <sstream> 

template <typename T> 
std::string toString(const T x, const int base) 
{ 
    std::stringstream ss; 
    ss << std::setbase(base) << x; 
    return ss.str(); 
} 

int main(void) 
{ 
    const int x = std::numeric_limits<int>::min(); 
    std::size_t index = 0; 
    const auto base = 16; 
    const auto s = toString(x, base); 
    std::cout << "base-10: " << x << std::endl 
       << "base-" << base << ": " << s << std::endl; 
    std::cout << std::stoi(s, &index, base) << std::endl; 
    return 0; 
} 

輸出:

base-10: -2147483648 
base-16: 80000000 
terminate called after throwing an instance of 'std::out_of_range' 
    what(): stoi 
Aborted (core dumped) 
+0

@ildjarn - 張貼作爲答案,我可以爲你upvote它:) – LThode 2015-02-09 21:29:35

+0

我找不到任何引用是否使用ss「std :: setbase(16)<< x;'是一個壞的想法負面'x'。即使對於'x = -10;'我也會看到使用你的代碼的問題。來自'ss << std :: setbase(base)<< x;'的字符串是'fffffff6',這對int來說可能也太大了。 – 2015-02-09 21:33:37

+1

這是因爲不一致:「std :: setbase(16)」或「std :: hex」將數字轉換爲無符號數,而「std :: stoi」處理有符號數。 – interjay 2015-02-09 21:35:49

回答

6

std::stoX功能不會爲不與-前綴字符串返回一個負值。 0x80000000是2 ,這是不能表示一個有符號的32位整數,所以有溢出,因此引發異常。

相關問題