函式模板
<string>

std::stof

float stof (const string&  str, size_t* idx = 0);float stof (const wstring& str, size_t* idx = 0);
將字串轉換為浮點數
解析str,將其內容解釋為浮點數,並將其作為型別為float.

的值返回。如果idx不是空指標,函式還會將idx的值設定為str中數字之後第一個字元的位置。

該函式使用 strtod (或 wcstod) 來執行轉換 (有關轉換過程的更多詳細資訊,請參閱 strtod)。請注意,這些函式接受的格式取決於當前區域設定。

引數

str
字串物件,包含浮點數的表示。
idx
指向型別為 size_t 的物件的指標,其值由函式設定為str中數值之後下一個字元的位置。
該引數也可以是一個空指標,此時它將不被使用。

返回值

成功時,函式將轉換後的浮點數作為型別為float.

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// stof example
#include <iostream>   // std::cout
#include <string>     // std::string, std::stof

int main ()
{
  std::string orbits ("686.97 365.24");
  std::string::size_type sz;     // alias of size_t

  float mars = std::stof (orbits,&sz);
  float earth = std::stof (orbits.substr(sz));
  std::cout << "One martian year takes " << (mars/earth) << " Earth years.\n";
  return 0;
}

可能的輸出
One martian year takes 1.88087 Earth years.


複雜度

未定義,但通常與解釋的字元數呈線性關係。

資料競爭

修改idx指向的值 (如果idx不為零)。

異常

如果無法執行轉換,則丟擲 invalid_argument 異常。
)。如果讀取的值超出了float(在某些庫實現中,這包括下溢),則丟擲 out_of_range 異常。

無效的idx會導致未定義行為

另見