c++ string to float
时间: 2023-09-11 19:13:16 浏览: 180
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
可以使用atof函数将C字符串转换为float类型。
例如:
```c
#include <stdio.h>
#include <stdlib.h>
int main() {
char str[] = "3.14";
float num = atof(str);
printf("The float number is %.2f\n", num);
return 0;
}
```
输出结果为:
```
The float number is 3.14
```
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`。
阅读全文