问题的字符串转换为数字

问题的字符串转换为数字

本文介绍了问题的字符串转换为数字(关于strtod)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的strtod()函数来提取环境变量作为一个字符串,然后改变其使用的strtod翻番:

I am using strtod( ) function to extract an environment variable as a string, and then changing it to double using strtod:

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);

现在我想确保用户输入的这个数字是一个数字,而不是一个字符串或特殊字符。我怎样才能确保这一点?

Now i want to make sure that this number entered by user is a number and not a string or special character. How can i make sure of that?

一个code段会有很大的帮助。

A code snippet would be of great help.

先谢谢了。

推荐答案

第二参数传递给的strtod 功能非常有用。

The 2nd argument to the strtod function is useful.

char *err;
d = strtod(userinput, &err);
if (*err == 0) { /* very probably ok */ }
if (!isspace((unsigned char)*err)) { /* error */ }


编辑:添加例子


examples added

的strtod 函数试图在第一个参数的初始部分转换为一张双人床和停止或者当没有更多的字符,或者有一个字符,可以' T为用于制造双

The strtod function tries to convert the initial portion of the 1st argument to a double and stops either when there are no more chars, or there is a char that can't be used to make a double.


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 == ' ')

这篇关于问题的字符串转换为数字(关于strtod)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 11:04