C++ String::stof() 函式



C++ 的std::string::stof()函式用於將字串轉換為浮點數。此函式分析字串,從字串開頭提取浮點值。如果轉換成功,則返回浮點值;否則,將丟擲invalid_argument異常。

語法

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

float stof (const string&  str, size_t* idx = 0);
float stof (const wstring& str, size_t* idx = 0);

引數

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

  • str − 表示包含浮點數表示形式的字串物件。
  • idx − 指向 size_t 型別物件的指標,函式將其值設定為 str 中數值之後下一個字元的位置。

返回值

此函式返回與作為引數傳遞的字串內容對應的浮點值。

示例 1

以下是用 C++ 使用 std::stof() 函式將字串轉換為浮點數的基本示例。

#include <string>
#include <iostream>
using namespace std;
int main() {
   string temperature = " 36.6";
   float bodyTemp = stof(temperature);
   cout << "Body temperature is " << bodyTemp << " degree Celsius" << endl;
   return 0;
}

輸出

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

Body temperature is 36.6 degree Celsius

示例 2

以下示例傳遞包含有效浮點數的子字串,跳過初始文字。

#include <string>
#include <iostream>
using namespace std;
int main() {
   string mixedContent = "Height: 180cm";
   size_t pos;
   float height = stof(mixedContent.substr(7), & pos);
   cout << "Height = " << height << " cm " << endl;
   return 0;
}

輸出

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

Height = 180 cm

示例 3

在這個例子中,我們使用 C++ 中的 string::stof 轉換單個字串中的多個數字。

#include <string>
#include <iostream>
#include <vector>
using namespace std;
int main() {
   string data = "3.14 1.618 2.718";
   vector < float > numbers;
   size_t pos = 0, prev_pos = 0;
   while ((pos = data.find(' ', prev_pos)) != string::npos) {
      numbers.push_back(std::stof(data.substr(prev_pos, pos - prev_pos), nullptr));
      prev_pos = pos + 1;
   }
   numbers.push_back(stof(data.substr(prev_pos), nullptr));
   for (float num: numbers) {
      cout << num << std::endl;
   }
   return 0;
}

輸出

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

3.14
1.618
2.718        

示例 4

在這個例子中,我們給出了無效的輸入,所以它會丟擲 invalid_argument 異常,因為該字串無法轉換為浮點數。

#include <string>
#include <iostream>
using namespace std;
int main() {
   string invalidNumber = "abc123";
   try {
      float value = stof(invalidNumber);
      cout << "Value is: " << value << std::endl;
   } catch (const invalid_argument & e) {
      cout << "Invalid argument: " << e.what() << endl;
   }
   return 0;
}

輸出

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

Invalid argument: stof          
string.htm
廣告