我有以下代码,但我觉得很脏..
我不喜欢写这么多ifs然后在每个if中重复代码.
关于如何改进此代码的任何想法?
char obj[5];
strlcpy(obj, &jarr[i], arr[i]);
if( !strcmp( obj, "led_r" ) ){
i++;
strlcpy( obj, &jarr[i], arr[i] );
red_brightness = atoi( obj );
Serial.print(" RED: ");
Serial.println( red_brightness );
}
if( !strcmp( obj, "led_g" ) ){
i++;
strlcpy( obj, &jarr[i], arr[i] );
green_brightness = atoi( obj );
Serial.print(" GREEN: ");
Serial.println( green_brightness );
}
if( !strcmp( obj, "led_b" ) ){
i++;
strlcpy( obj, &jarr[i], arr[i] );
blue_brightness = atoi( obj );
Serial.print(" BLUE: ");
Serial.println( blue_brightness );
}
Run Code Online (Sandbox Code Playgroud)
在此之前的其他答案也很好.这个答案的优点是你可以将选项名称更改为任何东西,它仍然可以工作.您还可以将此类选项解析扩展为更大的选项集.
// Assuming these are globals.
int red_brightness, green_brightness, blue_brightness;
// Use this array to help you parse.
static const struct {
const char *optionName;
int *brightness;
const char *label;
} ledOptions[] = {
{ "led_r", &red_brightness, " RED: " },
{ "led_g", &green_brightness, " GREEN: " },
{ "led_b", &blue_brightness, " BLUE: " },
};
// A handy macro for later.
#define DIM(array) (sizeof(array) / sizeof(array[0]))
...
// Now in your actual code:
strlcpy(obj, &jarr[i], arr[i]);
for (j=0;j<DIM(ledOptions);j++) {
if( !strcmp( obj, ledOptions[i].optionName ) ){
i++;
strlcpy( obj, &jarr[i], arr[i] );
*ledOptions[i].brightness = atoi( obj );
Serial.print(ledOptions[i].label);
Serial.println(*ledOptions[i].brightness);
}
}
Run Code Online (Sandbox Code Playgroud)