需要检查给定的字符串是否为常量值(int/long/double)?
这里 strtol 函数用于查找常量值。但面临问题
示例:
if(li1 = strtol (str,NULL,0))
printf("valid Integer ...");
str = "1"
输出 = 1.00str = "0.99999"
输出 = 0.00str = "tab"
输出 = 0.00
那如何通过查看输出来区分“0.99999”和“tab”呢?
最佳答案
对于整数,strtol
提供第二个参数,该参数将被设置为指向第一个不可转换的字符。
如果它不是空终止符 \0
,那么数字末尾就是垃圾。如果它等于原始字符串,则没有找到合适的字符。
例子:
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.
}
对于 float ,您需要使用 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
。
关于c - 在c中通过给定的字符串找出常量值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6435938/