Linux 字符串转换为数字的问题( strtod )

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5580975/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 03:33:52  来源:igfitidea点击:

Problem with string conversion to number ( strtod )

clinuxstringdoublestrtod

提问by kingsmasher1

I am using strtod( ) function to extract an environment variable as a string, and then changing it to double using 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);

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?

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

A code snippet would be of great help.

代码片段会有很大帮助。

Thanks in advance.

提前致谢。

采纳答案by pmg

The 2nd argument to the strtodfunction is useful.

strtod函数的第二个参数很有用。

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


Edit: examples added

编辑:添加了示例

The strtodfunction 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.

strtod函数尝试将第一个参数的初始部分转换为双精度值,并在没有更多字符或存在无法用于生成双精度值的字符时停止。

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

回答by Gareth McCaughan

That second argument to strtod, which you've set to NULL, can be a pointer-to-pointer-to-char; the pointer-to-char that it points to will get set to the character after the last thing strtodmanaged to parse. If that's the end of the string, or at least there's nothing after it but whitespace, then what you had was a number. Otherwise, it was something else.

strtod您已设置为 的第二个参数NULL可以是指向字符的指针;它指向的指向字符的指针将在最后一件事strtod设法解析后设置为字符。如果这是字符串的结尾,或者至少它后面只有空格,那么您所拥有的是一个数字。否则,它是别的东西。

回答by David

I don't know much about this language but I do know that strtod() will return 0.0 if the input is wrong. Maybe you could use a regular expression to validate the input string is a number.

我对这种语言不太了解,但我知道如果输入错误,strtod() 将返回 0.0。也许您可以使用正则表达式来验证输入字符串是否为数字。

回答by log0

man strtod: If no conversion is performed, zero is returned and the value of nptr is stored in the location referenced by endptr.

man strtod: 如果不进行转换,则返回零,并将 nptr 的值存储在 endptr 引用的位置。

char * endptr;
double d = strtod(strEnv, &endptr);
if (strEnv == endptr)
   /* invalid number */
else
   ...

回答by Johann Gerell

  • First, check the return value of getenv- if it's NULL, then that environment variable doesn't exist.
  • Second, if the return value of getenvisn't NULL, then you have the value, as a string.
  • Third, don't set the char ** endptrparameter of strtodto NULL, but use it to check the validity of the converted value, also check for 0.0.
  • 首先,检查getenv- 如果它是 NULL的返回值,则该环境变量不存在。
  • 其次,如果 的返回值getenv不为 NULL,那么您就有了作为字符串的值。
  • 第三,不要将char ** endptr参数设置strtod为NULL,而是用它来检查转换值的有效性,还要检查0.0.

回答by janneb

Surely you could do worse than just reading the man page for strtod() and acting upon that. E.g. on my Linux system it says:

当然,除了阅读 strtod() 的手册页并据此采取行动之外,您还可以做得更糟。例如在我的 Linux 系统上它说:

RETURN VALUE
       These functions return the converted value, if any.

       If  endptr  is  not  NULL,  a pointer to the character after the last character used in the conversion is stored in the location referenced by
       endptr.

       If no conversion is performed, zero is returned and the value of nptr is stored in the location referenced by endptr.

       If the correct value would cause overflow, plus or minus HUGE_VAL (HUGE_VALF, HUGE_VALL) is returned (according to the sign of the value), and
       ERANGE is stored in errno.  If the correct value would cause underflow, zero is returned and ERANGE is stored in errno.

That pretty much tells you what you need to do in order to handle errors. Also, like Johann Gerell said, you also need to check whether getenv() succeeded; a similar approach works there, i.e. check the man page and write error handling code according to that.

这几乎可以告诉您为了处理错误您需要做什么。另外,就像 Johann Gerell 所说的,您还需要检查 getenv() 是否成功;类似的方法在那里工作,即检查手册页并根据它编写错误处理代码。