我有一个C++结构
struct Line {
int date;
int time;
float open;
float high;
float low;
float close;
float sd;
float long_mo;
float short_mo;
};
8 个字段。
我想用循环填充它。
int fields_count=1;
while (fields_count<=8) {
// get digit from outer sourse. I dont need help here.
// First iteration puts to 1 field, Second iteration puts to 2 field and so on up to last field of struct
fields_count++;
}
像这样:
#include<stddef.h>
struct Line {
int date;
int time;
float open;
float high;
float low;
float close;
float sd;
float long_mo;
float short_mo;
};
char types [] = "iifffffff";
int offsets [] = {
offsetof (Line, date),
offsetof (Line, time),
offsetof (Line, open),
offsetof (Line, high),
offsetof (Line, low),
offsetof (Line, close),
offsetof (Line, sd),
offsetof (Line, long_mo),
offsetof (Line, short_mo)
}
Line line;
for (int i = 0; i < 9; i++) {
char *field_ptr = ((char*)&line) + offsets [i];
if (types [i] == 'i')
*(int*)field_ptr = readInt ();
else if (types [i] == 'f')
*(float*)field_ptr = readFloat ();
}