|
-
April 14th, 2006, 09:09 AM
#1
CSV reading (help pls)
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:
Code:
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
-
April 14th, 2006, 10:42 AM
#2
Re: CSV reading (help pls)
[bump] Could really do with any help on this [/bump]
-
April 14th, 2006, 11:29 AM
#3
Re: CSV reading (help pls)
use a std::vector instead ... see below for sample:
Code:
#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;
}
-
April 14th, 2006, 11:30 AM
#4
Re: CSV reading (help pls)
 Originally Posted by sheepdonkey
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):
 Originally Posted by sheepdonkey
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.
 Originally Posted by sheepdonkey
std::getline(ss,field,',');
You'd rather use istream::ignore.
"inherit to be reused by code that uses the base class, not to reuse base class code", Sutter and Alexandrescu, C++ Coding Standards.
Club of lovers of the C++ typecasts cute syntax: Only recorded member.
Out of memory happens! Handle it properly!
Say no to g_new()!
-
April 14th, 2006, 01:27 PM
#5
Re: CSV reading (help pls)
Thanks for the suggestions, they are just what I was looking for.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|