Friday, November 26, 2010

C++ read from CSV file

Simpe metod to read from a csv file:

#include "stdafx.h"

#include < string >
#include < vector >
#include< iostream >
#include< fstream >
 #include < math.h >

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    vector< vector< float > > descriptor;
    vector< float > classes;
    ifstream f;
    f.open("c:\\bayes.txt");
    while(f)
    {
        string str = "";
        f > >str;
        vector< float > desc;
        size_t found = str.find(",");
        while(found< 100 && found >0)
        {
            string t = str.substr(0,found);
            desc.push_back(strtod(t.c_str(), NULL));
            str = str.substr(found+1);
            found = str.find(",");
        }
        if(desc.size() >0)
        {
            descriptor.push_back(desc);
            classes.push_back(strtod(str.c_str(), NULL));
        }
     
    }

    f.close();


}

No comments:

Post a Comment