On 08/10/2012 02:09 PM,
john.chl...@gmail.com wrote:
> I have an entire file stored in a string. The file is 2 columns of doubles (stored in ASCII, of course). The doubles are separated by an arbitrary number of spaces, maybe tabs too.
>
> sscanf(file_bytes+offset, "%lf %lf", &x[i], &y[i]) will return the number of "items" read, in this case 2 doubles.
>
> I need to know how to increment "offset" to read the next line?
For this kind of work, what you need is strtod(), not sscanf().
Warning: untested code. As given below, it's uncompilable: it needs a
context that defines MAX_BYTES, file_bytes, x, and y, and fills in
file_bytes, and declares a function that the code below can be part of.
#include <errno.h>
#include <stdlib.h>
#include
const char *nptr = file_bytes;
for(int i=0; i<MAX_ITEMS && *nptr; i++)
{
char *endptr;
errno = 0;
x[i] = strtod(nptr, &endptr);
if(nptr == endptr)
{
fprintf(stderr, "x[%d]: \"%s\"\n is empty or does "
"not have the form expected by strtod()\n", i, nptr);
break;
}
else if(errno == ERANGE && fabs(x) >= HUGE_VAL)
{
fprintf(stderr, "x[%d]: strtod(\"%s\") overflowed\n", i, nptr);
break;
// ERANGE might or might not also be set on underflow.
}
else if(*endptr == '\0')
{
fprintf(stderr, "file ends without a y value for item %d\n", i);
break;
}
nptr = endptr;
errno = 0;
y[i] = strtod(nptr, &endptr);
// Insert similar error handling code here.
nptr = endptr;
}
The error handling here is just basic, it can be improved. In
particular, you should probably limit the number of bytes that are
printed from nptr: search for the end of the current line, and don't
print beyond that. I've left those details to be filled in by the student.