c语言读取csv文件和c++读取csv文件示例分享
本文导语: C读取csv文件 代码如下:#include #include 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') ...
C读取csv文件
#include
#include
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
#include
#include
#include
#include
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