将一串用逗号隔开的浮点数字符串转化成vector数组
时间: 2024-05-03 17:18:19 浏览: 27
可以使用C++中的stringstream和vector来实现。以下是代码示例:
```cpp
#include <iostream>
#include <sstream>
#include <vector>
using namespace std;
int main() {
string str = "1.2, 3.4, 5.6, 7.8"; // 浮点数字符串
vector<float> vec; // 存储浮点数的vector数组
stringstream ss(str); // 将字符串转化为stringstream对象
string token;
while (getline(ss, token, ',')) { // 按逗号分隔字符串
float num = stof(token); // 将分隔出来的字符串转化为浮点数
vec.push_back(num); // 将浮点数加入vector数组中
}
for (float num : vec) { // 输出vector数组中的元素
cout << num << " ";
}
cout << endl;
return 0;
}
```
输出结果为:1.2 3.4 5.6 7.8
相关问题
C代码将浮点数1.10000002转换成字符串数组
以下是将浮点数1.10000002转换为字符串数组的C代码:
```c
#include <stdio.h>
#include <string.h>
int main()
{
float f = 1.10000002;
char str[20];
// 将浮点数转换为字符串
sprintf(str, "%.8f", f);
// 输出字符串
printf("%s\n", str);
return 0;
}
```
输出结果为:
```
1.10000002
```
解释:
1. 使用sprintf函数将浮点数f转换为字符串,格式为"%.8f",其中%.8f表示输出的浮点数保留8位小数。
2. 将转换后的字符串存储到字符数组str中。
3. 输出字符数组str,即为转换后的浮点数字符串。
python 字符串数组转换为浮点数_Numpy将数组从浮点转换为字符串
将字符串数组转换为浮点数可以使用numpy的astype()方法,示例代码如下:
```python
import numpy as np
str_arr = np.array(['1.2', '3.4', '5.6'])
float_arr = str_arr.astype(np.float)
print(float_arr)
```
输出结果为:
```
[1.2 3.4 5.6]
```
将浮点数数组转换为字符串可以使用numpy的astype()方法,示例代码如下:
```python
import numpy as np
float_arr = np.array([1.2, 3.4, 5.6])
str_arr = float_arr.astype(np.str)
print(str_arr)
```
输出结果为:
```
['1.2' '3.4' '5.6']
```
相关推荐
![](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)