且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何检查存储为字符串的数字(双精度型)是否是 C++ 中的有效双精度数?

更新时间:2023-11-28 23:29:28

使用 strtod,它将字符串转换为双精度值并返回它无法解释为双精度值的一部分的任何字符.

use strtod, which converts a string to a double and returns any characters it couldn't interpret as part of the double.

double strtod(const char* nptr, char** endptr)

像这样:

char* input = "3.1456.365.12";
char* end;

strtod(input, &end);
if (*input == '\0')
{
  printf("fail due to empty string\n");
}
if (end == input || *end != '\0')
{
  printf("fail - the following characters are not part of a double\n%s\n", end);
}