C language read CSV file and c++ read CSV file sample share

  • 2020-04-02 02:16:44
  • OfStack

C reads the CSV file


#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("%st%st%sn", trim(name), trim(age), trim(birthday));
 }
 return 0;
}

C++ reads the CSV file


#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; 
 }
}


The CSV file

alice, 22, 1992/03/05
bob, 33, 1981/11/21
cart, 40, 1974/07/13


Related articles: