c语言读取csv文件和c++读取csv文件示例分享

时间:2021-05-20

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) = '\0';
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("%s\t%s\t%s\n", 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(" \t\r\n"));

str.erase(str.find_last_not_of(" \t\r\n") + 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

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章