kin*_*er1 6 c linux string double strtod
我使用strtod()函数将环境变量提取为字符串,然后使用strtod将其更改为double:
enter code here
char strEnv[32];
strncpy(strEnv, getenv("LT_LEAK_START"), 31);
// How to make sure before parsing that env LT_LEAK_START is indeed a number?
double d = strtod(strEnv, NULL);
Run Code Online (Sandbox Code Playgroud)
现在我想确保用户输入的这个数字是一个数字而不是字符串或特殊字符.我怎样才能确定?
代码片段会有很大帮助.
提前致谢.
pmg*_*pmg 16
strtod函数的第二个参数很有用.
char *err;
d = strtod(userinput, &err);
if (*err == 0) { /* very probably ok */ }
if (!isspace((unsigned char)*err)) { /* error */ }
Run Code Online (Sandbox Code Playgroud)
编辑:添加了示例
该strtod函数尝试将第一个参数的初始部分转换为double,并在没有更多字符时停止,或者存在不能用于生成double的char.
input result
---------- ----------------------------
"42foo" will return 42
and leave err pointing to the "foo" (*err == 'f')
" 4.5" will return 4.5
and leave err pointing to the empty string (*err == 0)
"42 " will return 42
and leave `err` pointing to the spaces (*err == ' ')
| 归档时间: |
|
| 查看次数: |
12575 次 |
| 最近记录: |