c语言读取csv文件和c++读取csv文件示例分享_C语言教程-查字典教程网
c语言读取csv文件和c++读取csv文件示例分享
c语言读取csv文件和c++读取csv文件示例分享
发布时间:2016-12-28 来源:查字典编辑
摘要:C读取csv文件复制代码代码如下:#include#includechar*trim(char*str){char*p=str;while(...

C读取csv文件

复制代码 代码如下:

#include <stdio.h>

#include <string.h>

char *trim(char *str)

{

char *p = str;

while (*p == ' ' || *p == 't' || *p == 'r' || *p == 'n')

p ++;

str = p;

p = str + strlen(str) - 1;

while (*p == ' ' || *p == 't' || *p == 'r' || *p == 'n')

-- p;

*(p + 1) = '';

return str;

}

int main()

{

FILE *fp = fopen("test.csv", "r");

if(fp == NULL) {

return -1;

}

char line[1024];

while(fgets(line, sizeof(line), fp)) {

//printf("%s", line);

char *save_ptr;

char *name = strtok_r(line, ",", &save_ptr);

if (name == NULL) {

return -1;

}

char *age = strtok_r(NULL, ",", &save_ptr);

char *birthday = strtok_r(NULL, ",", &save_ptr);

printf("%st%st%sn", trim(name), trim(age), trim(birthday));

}

return 0;

}

C++读取csv文件

复制代码 代码如下:

#include <iostream>

#include <fstream>

#include <sstream>

#include <string>

#include <vector>

using namespace std;

string Trim(string& str)

{

str.erase(0,str.find_first_not_of(" trn"));

str.erase(str.find_last_not_of(" trn") + 1);

return str;

}

int main()

{

ifstream fin("test.csv");

string line;

while (getline(fin, line)) {

//cout << line << endl;

istringstream sin(line);

vector<string> fields;

string field;

while (getline(sin, field, ',')) {

fields.push_back(field);

}

string name = Trim(fields[0]);

string age = Trim(fields[1]);

string birthday = Trim(fields[2]);

cout << name << "t" << age << "t" << birthday << endl;

}

}

csv文件

复制代码 代码如下:

alice,22,1992/03/05

bob,33,1981/11/21

cart,40,1974/07/13

相关阅读
推荐文章
猜你喜欢
附近的人在看
推荐阅读
拓展阅读
  • 大家都在看
  • 小编推荐
  • 猜你喜欢
  • 最新C语言学习
    热门C语言学习
    编程开发子分类