c++ string转float
时间: 2024-06-16 21:00:29 浏览: 165
在C++中,将字符串转换为浮点数可以使用以下方法:
1. 使用标准库函数stof():
```cpp
#include <string>
#include <iostream>
int main() {
std::string str = "3.14";
float f = std::stof(str);
std::cout << f << std::endl;
return 0;
}
```
这里使用了std::stof()函数将字符串转换为浮点数。注意,如果字符串无法转换为有效的浮点数,将会抛出std::invalid_argument异常。
2. 使用C函数sscanf():
```cpp
#include <cstdio>
#include <iostream>
int main() {
std::string str = "3.14";
float f;
sscanf(str.c_str(), "%f", &f);
std::cout << f << std::endl;
return 0;
}
```
这里使用了sscanf()函数,通过指定格式"%f"将字符串转换为浮点数。需要注意的是,sscanf()函数返回成功匹配的参数个数,如果返回值不等于1,则表示转换失败。
3. 使用C++11的std::stod()函数:
```cpp
#include <string>
#include <iostream>
int main() {
std::string str = "3.14";
double d = std::stod(str);
std::cout << d << std::endl;
return 0;
}
```
这里使用了std::stod()函数将字符串转换为双精度浮点数。与std::stof()类似,如果字符串无法转换为有效的浮点数,将会抛出std::invalid_argument异常。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)