2013-08-30 137 views
4

我給出了一個字符串y,我保證它只包含數字。在使用stoi函數將其存儲在int變量中之前,如何檢查它是否超出整數的範圍?在C++中檢查stoi()函數中的int限制

string y = "2323298347293874928374927392374924" 
int x = stoi(y); // The program gets aborted when I execute this as it exceeds the bounds 
       // of int. How do I check the bounds before I store it? 
+4

爲什麼不捕捉異常並相應地處理它? – PlasmaHH

+1

您可能需要閱讀有關解析字符串時出現問題的參考資料[如此](http://en.cppreference.com/w/cpp/string/basic_string/stol)。 –

+0

非常感謝你們!是的,我會通過參考! –

回答

8

您可以使用異常處理機制:

#include <stdexcept> 

std::string y = "2323298347293874928374927392374924" 
int x; 

try { 
    x = stoi(y); 
} 
catch(std::invalid_argument& e){ 
    // if no conversion could be performed 
} 
catch(std::out_of_range& e){ 
    // if the converted value would fall out of the range of the result type 
    // or if the underlying function (std::strtol or std::strtoull) sets errno 
    // to ERANGE. 
} 
catch(...) { 
    // everything else 
} 

detailed description of stoi function and how to handle errors

2

捕捉到了異常:

string y = "2323298347293874928374927392374924" 
int x; 

try { 
    x = stoi(y); 
} 
catch(...) { 
    // String could not be read properly as an int. 
} 
0

如果該字符串表示的值,這是一個合法的可能性太大以至於無法存儲在int中,請將其轉換到更大的東西,並檢查結果是否符合int

long long temp = stoll(y); 
if (std::numeric_limits<int>::max() < temp 
    || temp < std::numeric_limits<int>::min()) 
    throw my_invalid_input_exception(); 
int i = temp; // "helpful" compilers will warn here; ignore them. 
+1

如果長時間不合適會怎樣? –

+1

如果它不適合很長時間,它不是一個有效的整數值(忽略擴展的整數類型),並且您會得到一個異常。 –

+0

你也可以嘗試直接轉換爲int或所需的類型。 –