function template
<string>

std::stod

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

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

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

引數

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

返回值

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

示例

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

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

  double earth = std::stod (orbits,&sz);
  double moon = std::stod (orbits.substr(sz));
  std::cout << "The moon completes " << (earth/moon) << " orbits per Earth year.\n";
  return 0;
}

可能的輸出
The moon completes 12.3684 orbits per Earth year.


複雜度

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

資料競爭

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

異常

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

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

另見