我在使用C++编写的程序时遇到问题.我要求用户输入有效的号码.我把它作为一个字符串,因为我正在做的特定任务,从长远来看它使它更容易.对于基本错误检查,我想检查输入的数字是否是有效数字.例:
Enter number: 3.14
This would be valid
Enter number: 3.1456.365.12
This shouldn't be valid
Run Code Online (Sandbox Code Playgroud)
使用strtod,它将一个字符串转换为一个double,并返回任何不能解释为double的字符.
double strtod(const char* nptr, char** endptr)
Run Code Online (Sandbox Code Playgroud)
像这样:
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);
}
Run Code Online (Sandbox Code Playgroud)
我认为boost :: lexical_cast应该在这里帮助你