c语言读取csv文件和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;
}
#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;
}
}
alice, 22, 1992/03/05
bob, 33, 1981/11/21
cart, 40, 1974/07/13