如何检查存储为字符串的数字(双精度型)是否是 C++ 中的有效双精度数? [英] How can I check if a number (double type) stored as a string is a valid double number in C++?
本文介绍了如何检查存储为字符串的数字(双精度型)是否是 C++ 中的有效双精度数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在使用 C++ 编写的程序时遇到问题.我要求用户输入一个有效的数字.我把它当作一个字符串,因为我正在做的特定任务,从长远来看它更容易.对于基本的错误检查,我想检查输入的数字是否有效.示例:
I'm having an issue with a program I'm working on in C++. I am asking the user to input a valid number. I take it in as a string because the particular assignment I'm doing, it makes it easier in the long run. For basic error checking, I want to check to see if the number entered is a valid number. Example:
Enter number: 3.14
This would be valid
Enter number: 3.1456.365.12
This shouldn't be valid
推荐答案
使用 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);
}
这篇关于如何检查存储为字符串的数字(双精度型)是否是 C++ 中的有效双精度数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文