问题
I have a .csv file and I want to read the data in its format, not at string. This is the function that save the file in a readbuffer if is ok.
fileGetString(readbuffer,elcount(readbuffer),readHandle)!=0)
And I have the data is in this format:
Temperature;12.25;15.65;-25.12;80;
Time;1;2;4;7;
I want save the temperature in a buffer "Temperature[i]
"
and do the same with the time "Time[i]
"
How can I do this in CAPL?
I know that I can read each data like String and cast to integer or float doing some operations, but I want optimize code and read each data in its format.
回答1:
You can convert an string to an float number using strtod()
.
Just for fun, here is complete example:
on start
{
dword fh;
char text[255];
double Temperature[4], Time[4];
int i;
/* open file */
fh = openFileRead("a.csv",0);
if (!fh) {
write ("ERROR: Open file failed!");
return;
}
/* read the 'Temperature' line */
if (!fileGetString(text, elcount(text), fh) ||
strstr(text, "Temperature;") != 0) {
write("ERROR: Wrong file format, 'Temperature' not found!");
return;
}
/* get the 'Temperature' values */
getValuesFromCsvString(text, Temperature);
/* read the 'Time' line */
if (!fileGetString(text, elcount(text), fh) ||
strstr(text, "Time;") != 0) {
write("ERROR: Wrong file format, 'Time' not found!");
return;
}
/* get the 'Time' values */
getValuesFromCsvString(text, Time);
/* output values */
for (i = 0; i < elcount(Temperature); i++)
write("Temperature[%i] = %6.2f", i, Temperature[i]);
for (i = 0; i < elcount(Time); i++)
write("Time[%i] = %2.0f", i, Time[i]);
}
int getValuesFromCsvString(char text[], double vals[])
{
long i, pos;
double res;
pos = strstr(text, ";");
str_replace(text, ";", " ");
for (i = 0; i < elcount(vals) ; i++) {
pos = strtod(text, pos, res);
if (pos >= 0)
vals[i] = res;
else
break;
}
return 0;
}
Output:
Temperature[0] = 12.25
Temperature[1] = 15.65
Temperature[2] = -25.12
Temperature[3] = 80.00
Time[0] = 1
Time[1] = 2
Time[2] = 4
Time[3] = 7
来源:https://stackoverflow.com/questions/32482703/how-to-read-a-float-in-a-csv-with-capl