void parse_temperature(char *line) { char *temp_str; char *token; char *mode_str, *mu_str,*dms_str,*crtt_str; // 解析温度 if ((temp_str = strstr(line, "temp: ")) != NULL) { temp_str += strlen("temp: "); temp = strtof(temp_str, NULL); } if((mode_str = strstr(line,"WR mode: ")) != NULL){ mode_str += strlen("WR mode: "); int result = sscanf(mode_str,"%c",&mode); if(result != 1){ printf("mode is NULL!\n"); } } if(mode == "WRC_SLAVE_WR1"){ if((mu_str = strstr(line,"mu: ")) != NULL){ mu_str += strlen("mu: "); wr1_loopb = strtol(mu_str,NULL,10); } if((dms_str = strstr(line,"dms: ")) != NULL){ dms_str += strlen("dms: "); wr1_onew = strtol(dms_str,NULL,10); } if((crtt_str = strstr(line,"crtt: ")) != NULL){ crtt_str += strlen("crtt: "); wr1_linkt = strtol(crtt_str,NULL,10); } }else if(mode == "WRC_SLAVE_WR0"){ if((mu_str = strstr(line,"mu: ")) != NULL){ mu_str += strlen("mu: "); wr0_loopb = strtol(mu_str,NULL,10); } if((dms_str = strstr(line,"dms: ")) != NULL){ dms_str += strlen("dms: "); wr0_onew = strtol(dms_str,NULL,10); } if((crtt_str = strstr(line,"crtt: ")) != NULL){ crtt_str += strlen("crtt: "); wr0_linkt = strtol(crtt_str,NULL,10); } } } 优化代码
时间: 2024-03-11 14:47:08 浏览: 60
char.zip_char ** labview_entirecft_labview 字符串_labview 字符串_字符串
可以优化代码,将 if/else 分支语句中的相同代码提取出来,避免重复代码。例如:
```
void parse_temperature(char *line) {
char *temp_str;
char *token;
char *mode_str, *mu_str,*dms_str,*crtt_str;
// 解析温度
if ((temp_str = strstr(line, "temp: ")) != NULL) {
temp_str += strlen("temp: ");
temp = strtof(temp_str, NULL);
}
if((mode_str = strstr(line,"WR mode: ")) != NULL){
mode_str += strlen("WR mode: ");
int result = sscanf(mode_str,"%c",&mode);
if(result != 1){
printf("mode is NULL!\n");
}
if(mode == "WRC_SLAVE_WR1" || mode == "WRC_SLAVE_WR0") {
if((mu_str = strstr(line,"mu: ")) != NULL){
mu_str += strlen("mu: ");
if(mode == "WRC_SLAVE_WR1") {
wr1_loopb = strtol(mu_str,NULL,10);
} else {
wr0_loopb = strtol(mu_str,NULL,10);
}
}
if((dms_str = strstr(line,"dms: ")) != NULL){
dms_str += strlen("dms: ");
if(mode == "WRC_SLAVE_WR1") {
wr1_onew = strtol(dms_str,NULL,10);
} else {
wr0_onew = strtol(dms_str,NULL,10);
}
}
if((crtt_str = strstr(line,"crtt: ")) != NULL){
crtt_str += strlen("crtt: ");
if(mode == "WRC_SLAVE_WR1") {
wr1_linkt = strtol(crtt_str,NULL,10);
} else {
wr0_linkt = strtol(crtt_str,NULL,10);
}
}
}
}
}
```
这样可以减少代码冗余,提高代码的可读性和可维护性。
阅读全文