Click to See Complete Forum and Search --> : CSV reading (help pls)


sheepdonkey
April 14th, 2006, 09:09 AM
Is there a way to find out how long a line is in my csv file (e.g. how many variables). I'm reading the data into a string and then using stringstream (a method a picked up from this excellent forum!) to input into an array:

std::ifstream ifs(filename);
std::string line, field;

double* pArray = new double[11];

std::getline(ifs,line);
std::stringstream ss(line);

for(int i=0; i<11; i++)
{
ss>>pArray[i];
std::getline(ss,field,',');
}

Also, is this method accurate, as when I'm debugging and stepping through I see values change ever so slightly from what they are in the CSV file.

e.g.

0.4 in a CSV would be 0.4000000002

sheepdonkey
April 14th, 2006, 10:42 AM
Could really do with any help on this

Philip Nicoletti
April 14th, 2006, 11:29 AM
use a std::vector instead ... see below for sample:


#include <string>
#include <sstream>
#include <iostream>
#include <vector>

int main()
{
// std::ifstream ifs(filename);
std::string line, field;

std::vector<double> pArray;

double value;

// std::getline(ifs,line);
line = "1.2 , 2.033, 3.03 , 4.03";
std::stringstream ss(line);

while (ss >> value)
{
pArray.push_back(value);
std::getline(ss,field,',');
}

for (int i=0; i<pArray.size(); ++i)
{
std::cout << pArray[i] << "\n";
}

return 0;
}

SuperKoko
April 14th, 2006, 11:30 AM
0.4 in a CSV would be 0.4000000002

floating point values are not infinitely accurate.
They can't represent exactly decimal numbers.
There is not much you can do (except using greater floating point types):


double* pArray = new double[11];

Why do you dynamically allocate that.
A simple C-style array, or a std::vector (it it may be dynamic) would do the work, without memory leak.

std::getline(ss,field,',');

You'd rather use istream::ignore.

sheepdonkey
April 14th, 2006, 01:27 PM
Thanks for the suggestions, they are just what I was looking for.