对于整数,strtol 提供第二个参数,该参数将被设置为指向第一个不可转换的字符。
如果它是空终止符\0 以外的任何内容,则数字末尾有垃圾。如果它等于原始字符串,则 no 找到合适的字符。
例子:
char *str = "72";
char *estr;
float val = strtol (str, &estr, 10);
if (estr == str) {
// there was no convertible characters.
}
if (*estr != '\0') {
// there was rubbish at the end.
}
if (errno != 0) {
// underflow/overflow.
}
对于浮点,您需要使用strtoX 函数之一。
它的作用与strtol 函数非常相似。
示例用法:
char *str = "0.9999";
char *estr;
float val = strtof (str, &estr);
if (estr == str) {
// there was no convertible characters.
}
if (*estr != '\0') {
// there was rubbish at the end.
}
if (errno != 0) {
// underflow/overflow.
}
下面的完整程序显示了一个计算字符串表示的类型的函数:
#include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>
#define TYP_INTEGRAL 0
#define TYP_FLOATING 1
#define TYP_BAD 2
int getTypeAndData (char *str, long *valL, float *valF) {
char *end;
*valL = strtol (str, &end, 10);
if ((end != str) && (*end == '\0'))
return TYP_INTEGRAL;
*valF = strtof (str, &end);
if ((end != str) && (*end == '\0'))
return TYP_FLOATING;
return TYP_BAD;
}
int main (int argc, char *argv[]) {
char *desc[] = {"INT", "FLT", "BAD"};
int i, typ;
long lvar;
float fvar;
for (i = 1; i < argc; i++) {
lvar = 0; fvar = 0;
typ = getTypeAndData (argv[i], &lvar, &fvar);
printf ("%s: [%-10s] %10ld %10.3f\n", desc[typ], argv[i], lvar, fvar);
}
return 0;
}
使用myprog 12345 hello 12.7 1e2 0.4 .1 "" 0 运行时,输出为:
INT: [12345 ] 12345 0.000
BAD: [hello ] 0 0.000
FLT: [12.7 ] 12 12.700
FLT: [1e2 ] 1 100.000
FLT: [0.4 ] 0 0.400
FLT: [.1 ] 0 0.100
BAD: [ ] 0 0.000
INT: [0 ] 0 0.000
您可以看到它至少检测到了我可以快速提出的单元测试用例。
请注意,这并不直接传达下溢和上溢条件。在这些情况下会返回默认值,因为它们通常是明智的选择,但如果您想捕捉这些条件,可以在返回后查看errno。