支持的字符串类型有:
十六进制类型,例如:"0x123", "0X123"
整数类型,例如:"1000","-1000"
浮点数类型,例如:"0x789","0X789","1.345","-1.345","1.23e-5", "1.23E-5" ,"-1.23E+5"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
bool str_to_int(const char* str, const int len, int *result) {
bool is_hax_x = false;
for (int index = 0; index < len; index++) {
if ((str[index] >= '0') && (str[index] <= '9')) {
continue;
} else if ((str[index] == '-') || (str[index] == '+')) {
if (index != 0) {
return false;
} else {
continue;
}
} else if ((str[index] == 'x') || (str[index] == 'X')) {
if (is_hax_x) {
return false;
}
is_hax_x = true;
if ((index != 1) || (str[index-1] != '0')) {
return false;
} else {
continue;
}
} else {
return false;
}
}
if (is_hax_x) {
if (1 != sscanf(str, "%x", result)) {
return false;
}
} else {
if (1 != sscanf(str, "%d", result)) {
return false;
}
}
return true;
}
bool str_to_float(const char* str, const int len, float *result) {
bool is_has_point = false;
for (int index = 0; index < len; index++) {
if ((str[index] >= '0') && (str[index] <= '9')) {
continue;
} else if ((str[index] == '-') || (str[index] == '+')) {
if (index != 0) {
return false;
} else {
continue;
}
} else if ((str[index] == 'e') || (str[index] == 'E')) {
if (!is_has_point) {
return false;
}
int tmp_int = 0;
if (str_to_int(str+index+1, len-index-1, &tmp_int)) {
break;
} else {
return false;
}
} else if (str[index] == '.') {
if (is_has_point) {
return false;
}
is_has_point = true;
} else if ((str[index] == 'x') || (str[index] == 'X')) {
int tmp_int = 0;
if (str_to_int(str, len, &tmp_int)) {
break;
} else {
return false;
}
} else {
return false;
}
}
if (1 != sscanf(str, "%f", result)) {
return false;
}
return true;
}
int main() {
const char *tmp_a = "1.23e-3"; // 1.23e-3 0x778 1.222
int tmp_int;
float tmp_float;
bool is_ok;
is_ok = str_to_int(tmp_a, strlen(tmp_a), &tmp_int);
if (is_ok) {
printf("is int = %d\n", tmp_int);
}
is_ok = str_to_float(tmp_a, strlen(tmp_a), &tmp_float);
if (is_ok) {
printf("is float = %f\n", tmp_float);
}
return 0;
}