2017-09-28 52 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