Bumbala said:
Hello,
I just want to read a space delimited string of numbers into an array
of double. Is it possible with sscanf ?
Example:
double numbers[3];
char *line = "1 2.5 3.7";
sscanf(line, {format?}, numbers);
Also is the reverse possible with printf ?
sprintf(line, {format?}, numbers);
There are no *printf() or *scanf() conversion specifiers
for arrays (except for string-like things), so you'll have to
convert your numbers one at a time:
sscanf(line, "%lf%lf%lf",
&numbers[0], &numbers[1], &numbers[2]);
Hmm. Preprocessor to the partial rescue, for cases where the number of
arguments is fixed:
#define FM_1(X) X
#define FM_2(X) X X
#define FM_3(X) X X X
/* ... */
#define FM_9(X) X X X X X X X X X
#define AR(X, N, Y) X N Y
#define AR_1(X,Y) AR(X, 0, Y)
#define AR_2(X,Y) AR_1(X, Y), AR(X, 1, Y)
#define AR_3(X,Y) AR_2(X, Y), AR(X, 2, Y)
/* ... */
#define AR_9(X,Y) AR_8(X, Y), AR(X, 8, Y)
Now you can do things like:
printf(FM_3("%d"), AR_3(foo[,]))
This expands like:
printf("%d" "%d" "%d", foo[ 0 ], foo[ 1 ], foo[ 2 ])
You can visualize the comma in the AR_3 syntax not as being a macro argument
separator, but as a meta-variable which indicates where the array index will be
inserted.
AR stands both for argument and array.
The FM_<n> ought to be more sophisticated, or have more sophisticated
alternatives, where you can control things like material that occurs between
the format directives, but not after the last one.
#define FMS_1(X, Y) X
#define FMS_2(X, Y) X Y X
#define FMS_3(X, Y) X Y X Y X
printf(FMS_3("%02x", ":"), ...) // colon-separation, e.g. MAC
Or alternative approach: Y specifies alternative for the last conversion
specifier:
#define FMA_1(X, Y) Y
#define FMA_2(X, Y) X Y
#define FMA_3(X, Y) X X Y
printf(FMA_3("%02x:", "%02x"), ...) // colon-separation, differently
Though this can be expressed
printf(FM_2("%02x:"), "%02x", ...) // colon-separation, differently
there is still value in maintaining the encapsulation.