#include <cstring>
#include <string>
#include <fstream>
Template<class callbackfun> bool Csvread (const char* filename, callbackfun CBF, Char delimit= ', ')
{
Std::ifstream file (filename, std::ios::binary);
if (!file) return false; File Open failed
BOOL Quo = false; Whether this field starts with double quotes
BOOL Quopre = false; When this field starts with double quotes, whether the previous one is a double quote
Std::string Val;
size_t row=0, col=0;
for (char C; file.get (c);)
{
if (c = = delimit)
{
if (Quo &&!quopre)
{
val = c;
}
Else
{
if (!CBF (Row,col,val))
return false;
Quo = false;
Quopre = false;
Val.clear ();
++col;
}
}
else switch (c)
{
Case ' "':
if (!quo)
{
if (Val.empty ())
Quo = true;
Else
val = c;
}
else if (quopre)
{
Quopre = false;
val = c;
}
Else
Quopre = true;
Break
Case ' \ R ':
Break
Case ' \ n ':
if (quo)
{
val = c;
}
Else
{
if (!CBF (Row,col,val))
return false;
Quo = false;
Quopre = false;
Val.clear ();
++row;
col = 0;
}
Break
Default
if (Quopre)
{
Quo = false;
Quopre = false;
}
val = c;
Break
}
}
if (!val.empty () | | col!=0)
{
if (!CBF (Row,col,val))
return false;
}
return file.eof ();
}
void Csvvalue (const char* STR, std::string& val)
{
if (str[strcspn (str, ", \ \ n")] = = ' yes ')
{
Val.clear ();
Return
}
If you have a comma-delimited line, enclose it in quotes and change the quotation marks to double
val = ' "';
Const char* P1 = str;
for (const char* P2; (P2=STRCHR (P1, ' "))!=0; P1=P2+1)
{
Val.append (P1, p2-p1+1);
Val.append (1, ' ");
}
Val.append (p1);
Val.append (1, ' ");
Return
}
The following is a test////////////////////
#include <iostream>
#include <locale>
using namespace Std;
struct FOO
{
Foo (): Row (0), col (0)
{
}
size_t Row, col;
BOOL Operator () (size_t R, size_t C, std::string val)
{
if (r!= Row)
cout << ' \ n ';
if (c!= 0)
cout << ' | ';
cout << Val;
Row=r, Col=c;
return true;
}
};
int main ()
{
Otherwise, open the path containing Chinese failed, but unfortunately MinGW with the invalid, and do not support the "CHS"
Std::locale loc = Std::locale::global (Std::locale (Std::locale (), "", Std::locale::ctype));
Csvread ("C:\\Documents and settings\\0846\\ desktop \\Book1.csv", foo ());
Std::string Val;
Csvvalue ("\" A\ "\" b\ "\" ", Val);
return 0;
}