C++ String::stol() 函式



C++ 的std::string::stol()函式用於將字串轉換為長整數。它接收一個字串作為輸入,並將其轉換為長整型,帶有一個可選的基數引數用於數值轉換。此外,它還接收一個指向size_t型別的指標,用於儲存處理的字元數。如果轉換失敗,則丟擲invalid_argument異常。

語法

以下是std::string::stol()函式的語法。

long stol (const string&  str, size_t* idx = 0, int base = 10);
long stol (const wstring& str, size_t* idx = 0, int base = 10);

引數

  • str − 指示包含整數表示形式的字串物件。
  • idx − 指向size_t型別物件的指標,函式會將它的值設定為str中數值之後下一個字元的位置。
  • base − 指示數值基數,該基數決定有效字元及其解釋。

返回值

它將字串值返回為長整數。

示例 1

以下是如何使用C++將十進位制字串轉換為長整數的基本示例。

#include <iostream>
#include <string>
using namespace std;
int main() {
   string decimal = "123456";
   long int dec_num = stol(decimal);
   cout << "The long integer = " << dec_num << endl;
   return 0;
}

輸出

如果執行以上程式碼,將生成以下輸出。

The long integer = 123456

示例 2

在這個例子中,我們傳遞一個十六進位制字串來轉換為長整數。

#include <iostream>
#include <string>
using namespace std;
int main() {
   string hex = "987654F";
   long int hex_num = stol(hex, nullptr, 16);
   cout << "The long integer = " << hex_num << endl;
   return 0;
}

輸出

如果執行以上程式碼,將生成以下輸出。

The long integer = 159868239

示例 3

此程式從包含字母數字字元的字串中提取一個長整數,在第一個非數字字元處停止,並將整數列印到編譯器。

#include <iostream>
#include <string>
using namespace std;
int main() {
   string mixed = "10000px";
   size_t pos;
   long int number = stol(mixed, & pos);
   cout << "The long integer = " << number << endl;
   return 0;
}

輸出

以下是以上程式碼的輸出。

The long integer = 100000                

示例 4

此程式將24進位制字串“64B”轉換為其等效的長整數值。

#include <iostream>
#include <string>
using namespace std;
int main() {
   string base24 = "64B";
   long int base24_num = stol(base24, nullptr, 24);
   cout << "The long integer = " << base24_num << endl;
   return 0;
}

輸出

以下是以上程式碼的輸出。

The long integer = 3563
string.htm
廣告