當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


C++ std::stof用法及代碼示例


解析字符串,將其內容解釋為浮點數,該浮點數作為float類型的值返回。

用法:

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

參數:
str:String object with the representation of a floating-point number.
idx: Pointer to an object of type size_t, whose value is set by the function
to position of the next character in str after the numerical value.
This parameter can also be a null pointer, in which case it is not used.

返回值:
On success, the function returns the converted floating-point number as a value of type float.

以下是std::stof的C++實現:


// CPP code to convert floating  
// type number to string 
#include <bits/stdc++.h> 
  
int main() 
{ 
    // String to be parsed 
    std::string str = "100.80"; 
  
    // val to store parsed floating type number 
    float val = std::stof(str); 
  
    // Printing parsed floating type number 
    std::cout << val; 
  
    return 0; 
}

輸出:

100.8
// CPP code to convert integer  
// type number to string 
#include <bits/stdc++.h> 
  
int main() 
{ 
    // String to be parsed 
    std::string str = "1000"; 
  
    // val to store parsed integer type number 
    float val = std::stof(str); 
  
    // Printing parsed integer type number 
    std::cout << val; 
  
    return 0; 
}

輸出:

1000


相關用法


注:本文由純淨天空篩選整理自 std::stof in C++。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。