I have written the following function to accept a string from a csv text file that presumably contains a series of comma separated numbers.
double comma_read(int &index, const string &input)
// Reads a number from a comma delimited (csv) file
// Returns first number after index-th comma
// Then updates the index value to prepare for the next read
{
string accum="";
int commacount=0;
int position=0;
double out;
const int inputlength=int(input.length());
while (index!=commacount)
{
if (input[position]==',') commacount++;
position++;
}
if (input[position]==',') // data is blank
out=MISSING;
else if (position==inputlength) // data is blank at the end of the data line
out=MISSING;
else // data is not blank
{
while (input[position]!=',')
{
accum+=input[position];
position++;
if (position==inputlength) break;
}
char *p; // needed for strtod function
out=strtod(accum.c_str(), &p);
}
if (fabs(out - -3.70e28) <= ZERO) out=MISSING; // checking for old_csv missing data
index=commacount+1;
return out;
}
The function is return the double that is located after the index-th comma in the string.
You can see that I approach this problem by parsing the string, first looking for the index-th comma in the string. Once the index-th comma is found I accumlate the contents of string charcter by charter into the string accum until another comma is found or the end of line is reached. Then the accum string is converted to a double using the strtod function. The index updates so that I can use this function in a loop to read all the numbers in the line.
The question I have is, is the the most efficient way to accomlish this task?
Any ideas for improvement?
Thanks.