[英]Converting string to long
我正在嘗試將字符串轉換為long。 這聽起來很容易,但我仍然得到同樣的錯誤。 我試過了:
include <iostream>
include <string>
using namespace std;
int main()
{
string myString = "";
cin >> myString;
long myLong = atol(myString);
}
但總是錯誤:
.../main.cpp:12: error: cannot convert 'std::string {aka std::basic_string<char>}' to 'const char*' for argument '1' to 'long int atol(const char*)'
發生。 參考文獻如下:
long int atol ( const char * str );
有幫助嗎?
嘗試
long myLong = std::stol( myString );
該功能有三個參數
long stol(const string& str, size_t *idx = 0, int base = 10);
您可以使用第二個參數來確定字符串中解析數字的位置的位置。 例如
std::string s( "123a" );
size_t n;
std::stol( s, &n );
std::cout << n << std::endl;
輸出是
3
該函數可以拋出異常。
只需寫長myLong = atol(myString.c_str());
atol()
需要一個const char*
; 沒有從std::string
到const char*
的隱式轉換,所以如果你真的想使用atol()
,你必須調用std::string::c_str()
方法來獲得原始的類C字符串指針傳遞給atol()
:
// myString is a std::string
long myLong = atol(myString.c_str());
更好的C ++方法是使用stol()
(自C ++ 11以來可用),而不依賴於像atol()
這樣的C函數:
long myLong = std::stol(myString);
atol
獲取const char*
(C樣式字符串)作為參數,但是您將作為參數傳遞給std::string
。 編譯器無法在const char*
和std::string
之間找到任何可行的轉換,因此它會給出錯誤。 您可以使用string
成員函數std::string::c_str()
,它返回一個c樣式的字符串,相當於std::string
的內容。 用法:
string str = "314159265";
cout << "C-ctyle string: " << str.c_str() << endl;
cout << "Converted to long: " << atol(str.c_str()) << endl;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.