C Read CSV file
Copy Code code as follows:
#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 (line, sizeof (line), FP) {fgets
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 + + read CSV file
Copy Code code as follows:
#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 file
Copy Code code as follows:
Alice, 22, 1992/03/05
Bob, 33, 1981/11/21
Cart, 40, 1974/07/13