[lib-result] Add read_float_field() and use it

This function is similar to owl_read_long_field() but reads a float and
doesn't allow to choose an alternative field delimiter.
This commit is contained in:
Matteo Cypriani 2013-09-24 17:03:22 -04:00
parent 21e624728c
commit 5d71ca9ae2
2 changed files with 40 additions and 12 deletions

View File

@ -212,44 +212,36 @@ owl_algorithm_result* owl_fill_algorithm_result(char **csv)
strndup(csv_field, OWL_ALGORITHM_STRLEN) ;
// X coordinate
csv_field = strsep(csv, CSV_DELIMITER) ;
if (! csv_field)
if (! owl_read_float_field(csv, &algo->x))
{
fprintf(stderr,
"Error reading the X coordinate from the CSV string!\n") ;
goto error ;
}
algo->x = atof(csv_field) ;
// Y coordinate
csv_field = strsep(csv, CSV_DELIMITER) ;
if (! csv_field)
if (! owl_read_float_field(csv, &algo->y))
{
fprintf(stderr,
"Error reading the Y coordinate from the CSV string!\n") ;
goto error ;
}
algo->y = atof(csv_field) ;
// Z coordinate
csv_field = strsep(csv, CSV_DELIMITER) ;
if (! csv_field)
if (! owl_read_float_field(csv, &algo->z))
{
fprintf(stderr,
"Error reading the Z coordinate from the CSV string!\n") ;
goto error ;
}
algo->z = atof(csv_field) ;
// Distance error
csv_field = strsep(csv, CSV_DELIMITER) ;
if (! csv_field)
if (! owl_read_float_field(csv, &algo->error))
{
fprintf(stderr,
"Error reading the distance error from the CSV string!\n") ;
goto error ;
}
algo->error = atof(csv_field) ;
// Area name (optional)
csv_field = strsep(csv, CSV_DELIMITER) ;
@ -302,6 +294,41 @@ bool owl_read_long_field(char **const csv, const char *const delim,
}
/**
* Reads the first field from the `csv` string as a float and stores it
* in `ret`. `csv` will be modified to point to the next field.
*
* @param[in,out] csv The CSV string.
* @param[out] ret The float value read from the field.
*
* @returns `true` in case of success.
* @returns `false` in case of error.
*/
bool owl_read_float_field(char **const csv, float *const ret)
{
char *endptr = NULL, *csv_field = NULL ;
csv_field = strsep(csv, CSV_DELIMITER) ;
if (! csv_field)
{
fprintf(stderr,
"Error reading a field from the CSV string!\n") ;
return false ;
}
*ret = strtof(csv_field, &endptr) ;
if (endptr == csv_field)
{
fprintf(stderr,
"The field does not contain a valid floating-point"
" value!\n") ;
return false ;
}
return true ;
}
/**
* Converts an `owl_result` back to a CSV string.
* `dst` must be an allocated string of at least `OWL_CSV_RESULT_STRLEN`

View File

@ -116,6 +116,7 @@ owl_algorithm_result* owl_fill_algorithm_result(char **csv) ;
/// Reads an integer from the `csv` string
bool owl_read_long_field(char **const csv, const char *const delim,
long *const ret) ;
bool owl_read_float_field(char **const csv, float *const ret) ;
/// Converts an `owl_result back` to a CSV string
void owl_result_to_csv(char dst[OWL_CSV_RESULT_STRLEN],