C语言读取鸢尾花数据集
时间: 2023-07-09 21:05:02 浏览: 51
读取鸢尾花数据集可以使用C语言中的文件操作函数来实现。这里提供一种读取csv格式数据集的方法,具体实现如下:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LINE_LENGTH 1024 // 定义每行最大长度
int main()
{
FILE *fp = NULL;
char line[MAX_LINE_LENGTH];
char *token = NULL;
float sepal_length, sepal_width, petal_length, petal_width;
int label;
fp = fopen("iris.data", "r"); // 打开数据集文件
if(fp == NULL)
{
printf("Failed to open the file!\n");
return -1;
}
while(fgets(line, MAX_LINE_LENGTH, fp) != NULL) // 逐行读取数据
{
token = strtok(line, ","); // 以逗号为分隔符,分割每行数据
sepal_length = atof(token); // 将字符串转换为浮点数
token = strtok(NULL, ",");
sepal_width = atof(token);
token = strtok(NULL, ",");
petal_length = atof(token);
token = strtok(NULL, ",");
petal_width = atof(token);
token = strtok(NULL, ",");
label = atoi(token);
printf("%f, %f, %f, %f, %d\n", sepal_length, sepal_width, petal_length, petal_width, label);
}
fclose(fp); // 关闭文件
return 0;
}
```
以上代码会打开当前目录下的iris.data文件,逐行读取每条数据,并将其转换为浮点数和整数。注意,此处假设数据集文件的每行数据格式为“sepal_length, sepal_width, petal_length, petal_width, label”。如果实际数据格式不同,需要对代码进行相应修改。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![c](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)