2013-08-30 183 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或所需的类型。 –