C语言读取csv文件并保存到数组中

前言

csv是常用的数据文件格式,在R、Python、Matlab这些语言中,读取csv是一件很容易的事情,那用最经典的c如何来读取csv呢?

要读取的文件

在这里插入图片描述

读取的代码

下面就来看看代码吧

#include <iostream>
#include <fstream>
#include <iomanip>
#include <sstream>
#include <string>
using namespace std;

int main()
{

    int len_x=5921;
    double x[len_x];
    ifstream inFile("gene_new.CSV", ios::in);
    if (!inFile)
    {
        cout << "打开文件失败!" << endl;
        exit(1);
    }
    int i = 0;
    string line;
    string field;
    while (getline(inFile, line))//getline(inFile, line)表示按行读取CSV文件中的数据
    {
        string field;
        istringstream sin(line); //将整行字符串line读入到字符串流sin中

        getline(sin, field, ','); //将字符串流sin中的字符读入到field字符串中,以逗号为分隔符
//        cout<<atof(field.c_str())<<" ";//将刚刚读取的字符串转换成int
        x[i]=atof(field.c_str());
        i++;
    }
    inFile.close();
//    看看建立的数组好了没
    for(i=0;i<len_x;i++)
    {
        cout<<"NO."<<i+1<<":"<<x[i]<<endl;
    }
    return 0;
}

结果

在这里插入图片描述

  • 10
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
可以使用 C++文件读写操作来读取学生信息文件内容到学生数组中。以下是一个示例代码: ```c++ #include <iostream> #include <fstream> #include <string> using namespace std; struct Student { string name; int age; string gender; }; int main() { const int MAX_STUDENTS = 100; Student students[MAX_STUDENTS]; int num_students = 0; ifstream infile("students.txt"); if (infile.is_open()) { string line; while (getline(infile, line)) { Student student; student.name = line; infile >> student.age >> student.gender; students[num_students++] = student; infile.ignore(); // ignore the newline character } infile.close(); } else { cout << "Unable to open file" << endl; return 1; } // print the contents of the array for (int i = 0; i < num_students; i++) { cout << students[i].name << " " << students[i].age << " " << students[i].gender << endl; } return 0; } ``` 在上面的代码中,我们首先定义了一个 `Student` 结构体来存储每个学生的信息。然后我们定义了一个大小为 `MAX_STUDENTS` 的 `students` 数组来存储所有学生的信息,并用 `num_students` 变量来记录实际读取到的学生数量。 接下来,我们使用 `ifstream` 对象来打开名为 `students.txt` 的文件,并进行读取操作。在每次循环中,我们首先读取一行学生姓名,并将其存储到 `student.name` 中。接着,我们使用 `>>` 运算符来从文件读取学生的年龄和性别,并将它们存储到 `student.age` 和 `student.gender` 中。最后,我们将 `student` 对象存储到 `students` 数组中,并将 `num_students` 加 1。在每次循环结束后,我们使用 `ignore` 函数来忽略掉读取操作时留下的换行符。 最后,我们在循环外打印 `students` 数组中所有学生的信息,以验证读取操作是否成功。 注意,上面的示例代码中假设学生信息文件每行只包含一个学生的信息,即每行依次为学生姓名、年龄和性别。如果学生信息文件的格式不同,例如每个学生的信息分别存储在不同的行中,那么需要进行相应的更改。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值