2017-09-28 51 views
-1

我需要将带有数字的字符串转换为long变量以执行一些数学运算。
现在我用std::stol来做到这一点,但是当我插入一个值太大的方法无法处理它,它停止与argument out of range
所以我的问题是:是否有一种方法来转换长(或长)类型的字符串没有内存不足?将C++字符串转换为long而没有out_of_range异常

这是我使用的代码:

#include <iostream> 

int main() { 

std::string value = "95666426875"; 
long long converted_value = std::stoul(value.c_str()); 
//Some math calc here 
std::cout << converted_value << std::endl; 

return 0; 

}

+0

做你想做的事,当输入值过大,以适应什么? –

回答

2

貌似long是32位宽的平台上,让95666426875太大,以适应32位long

使用stoull解析为unsigned long long而不是stoul。例如:

auto converted_value = std::stoull(value); 

(请注意,您无需致电value.c_str())。

+1

此外,可能会丢失从'unsigned long long'到'long long'的数据转换,所以要么变量应该是'unsigned long long'或者'stoll'应该被调用。不过,我觉得使用'long long'可能是OP的一种方案,但我不能肯定地说。 – chris

+0

@chris用'auto'添加了一个例子。 –

+0

@MaximEgorushkin你的答案的问题是,我发布的代码中的示例值是一个用户输入变量,所以我不知道用户是否会插入一个更大的值..因为我试图插入更大的东西,程序已经停止了同样的错误(即使用'auto'而不是'unsigned long long') – zDoes

0

您可以使用stringstream还有:

#include <iostream> 
#include <sstream> 

int main() 
{ 
    std::string value = "95666426875"; 

    //number which will contain the result 
    unsigned long long Result; 

    // stringstream used for the conversion initialized with the contents of value 
    std::stringstream ss_value (value); 

    //convert into the actual type here 
    if (!(ss_value >> Result)) 
    { 
     //if that fails set Result to 0 
     Result = 0; 
    } 

    std::cout << Result; 

    return 0; 
} 

运行它自己:link