c++ string to float
时间: 2023-09-11 07:13:16 浏览: 39
To convert a C++ string to a float, you can use the `std::stof` function from the `<string>` library. Here's an example:
```cpp
#include <iostream>
#include <string>
int main() {
std::string str = "3.14";
float floatValue = std::stof(str);
std::cout << "Float value: " << floatValue << std::endl;
return 0;
}
```
In this example, the `std::stof` function takes the string `str` and converts it to a float value. The resulting float value can then be used as needed.
相关问题
c++string转float
你可以使用`std::stof`函数将C风格的字符串转换为浮点数。它是C++标准库中的函数,可以将字符串转换为float类型。以下是一个示例:
```cpp
#include <iostream>
#include <string>
int main() {
const char* str = "3.14";
float result = std::stof(str);
std::cout << "Float value: " << result << std::endl;
return 0;
}
```
在上面的示例中,我们将字符串"3.14"转换为浮点数,并将结果存储在`result`变量中。然后,我们通过`std::cout`将结果打印到标准输出。输出将显示为`3.14`。
c++ string 转 float
你可以使用`std::stof`函数将`std::string`类型的字符串转换为`float`类型。以下是一个示例:
```cpp
#include <iostream>
#include <string>
int main() {
std::string str = "3.14";
float f = std::stof(str);
std::cout << "Converted float value: " << f << std::endl;
return 0;
}
```
这段代码将字符串"3.14"转换为对应的浮点数,并将结果存储在变量`f`中。你可以根据需要修改字符串的值。