C++ String::stoi() 函式



C++ 的std::string::stoi()函式用於將字串轉換為整數 (int)。此函式將字串的初始字元分析為整數,並在遇到第一個非數字字元時停止。如果轉換成功,則返回整數的值,否則丟擲 invalid_argument 異常。

語法

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

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

引數

此函式有兩個引數,如下所述。

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

返回值

它返回已解析字串的整數值。

示例 1

以下是使用 C++ 演示 string::stoi 的基本轉換的基本示例。

#include <iostream>
#include <string>
using namespace std;
int main() {
   string s = "42";
   int num = stoi(s);
   cout << num << endl;
   return 0;
}

輸出

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

42

示例 2

在此示例中,我們正在處理十六進位制和二進位制字串以進行整數轉換。

#include <iostream>
#include <string>
using namespace std;
int main() {
   string hexStr = "2A";
   string binStr = "101010";
   int numHex = stoi(hexStr, nullptr, 16);
   int numBin = stoi(binStr, nullptr, 2);
   cout << numHex << ", " << numBin << endl;
   return 0;
}

輸出

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

42, 42

示例 3

在以下示例中,我們正在從混合字串中提取數字。

#include <iostream>
#include <string>
using namespace std;
int main() {
   string mixedStr = "Year2024";
   int year = stoi(mixedStr.substr(4));
   cout << year << endl;
   return 0;
}

輸出

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

2024                 

示例 4

以下是一個演示 string:stoi() 函式的另一個示例。此處傳遞了字串,但該字串不包含任何有效數字,即數值。因此,它引發了 invalid_argument 異常。

#include <iostream>
#include <string>
using namespace std;
int main() {
   string invalidStr = "Tutorialspoint";
   try {
      int num = stoi(invalidStr);
   } catch (const std::invalid_argument & e) {
      cout << "Invalid input: " << e.what() << endl;
   }
   return 0;
}

輸出

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

Invalid input: stoi 
string.htm
廣告